simple c++ BFS


  • 0
    W
    int INF = 2147483647;
    void dfs_wag(vector<vector<int>>& r, int row, int col, int steps)
    {
    	if (row < 0 || row > r.size() - 1) return;
    	if (col < 0 || col > r[0].size() - 1) return;
    	if (r[row][col] == -1) return;
    	if (r[row][col] != INF && r[row][col] < steps) return;
    
    	r[row][col] = steps;
    
    	dfs_wag(r, row + 1, col, steps + 1);
    	dfs_wag(r, row - 1, col, steps + 1);
    	dfs_wag(r, row, col + 1, steps + 1);
    	dfs_wag(r, row, col - 1, steps + 1);
    }
    void wallsAndGates(vector<vector<int>>& rooms) {
    
    	for (int i = 0; i < rooms.size(); ++i) {
    		for (int j = 0; j < rooms[0].size(); ++j) {
    			if (rooms[i][j] == 0) {
    				dfs_wag(rooms, i, j, 0);
    			}
    		}
    	}
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.