[LeetCode286]Walls and Gates

You are given a m x n 2D grid initialized with these three possible values.

1.-1 - A wall or an obstacle.
2.0 - A gate.
3.INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647.
Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF.

For example, given the 2D grid:
    INF  -1  0  INF
    INF INF INF  -1
    INF  -1 INF  -1
    0  -1   INF  INF
After running your function, the 2D grid should be:
  3  -1   0   1
  2   2   1  -1
  1  -1   2  -1
  0  -1   3   4
Hide Company Tags Facebook
Hide Tags Breadth-first Search
Hide Similar Problems (M) Surrounded Regions (M) Number of Islands

這題好像見過類似的, 所以一下子就知道遍歷整個2d grid, 遇見0就開始dfs四個方向更新如果是ifn的值。

class Solution {
public:
    void wallsAndGates(vector<vector<int>>& rooms) {
        if(rooms.empty()) return;
        int n = rooms.size(), m = rooms[0].size();
        for(int i = 0; i<n; ++i){
            for(int j = 0; j<m; ++j){
                if(!rooms[i][j]) update(rooms, i, j, 0);
            }
        }
    }
    void update(vector<vector<int>>& rooms, int i, int j, int initial){
        if (i<0 || i>=rooms.size() || j<0 || j>=rooms[0].size() || rooms[i][j] < initial) return;
        rooms[i][j] = initial;
        vector<pair<int, int>> dirs = {{i+1, j}, {i-1, j}, {i, j+1}, {i, j-1}};
        for (const pair<int, int>& dir : dirs) update(rooms, dir.first, dir.second, initial+1);
    }
};

或者可以BFS:

void wallsAndGates(vector<vector<int>>& rooms) {
        const int row = rooms.size();
        if (0 == row) return;
        const int col = rooms[0].size();
        queue<pair<int, int>> canReach;  // save all element reachable
        vector<pair<int, int>> dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; // four directions for each reachable
        for(int i = 0; i < row; i++){
            for(int j = 0; j < col; j++){
                if(0 == rooms[i][j])
                    canReach.emplace(i, j);
            }
        }
        while(!canReach.empty()){
            int r = canReach.front().first, c = canReach.front().second;
            canReach.pop();
            for (auto dir : dirs) {
                int x = r + dir.first,  y = c + dir.second;
                // if x y out of range or it is obstasle, or has small distance aready
                if (x < 0 || y < 0 || x >= row || y >= col || rooms[x][y] <= rooms[r][c]+1) continue;
                rooms[x][y] = rooms[r][c] + 1;
                canReach.emplace(x, y);
            }
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章