[LeetCode] 286. 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

 给一个m*n 的二维方格,开始里面有-1代表墙或者障碍物,0代表门,INF 代表空房间。把空房间用离它最近的门的距离填充,如果没有能到达的门,则填充 INF。

解法1:DFS,搜索0的位置,每找到一个0,以其周围四个相邻点为起点,开始DFS遍历,并带入深度值1,如果遇到的值大于当前深度值,将位置值赋为当前深度值,并对当前点的四个相邻点开始DFS遍历,注意此时深度值需要加1,这样遍历完成后,所有的位置就被正确地更新了。

解法2:BFS

Java: DFS

public void wallsAndGates(int[][] rooms) {
    if(rooms==null || rooms.length==0||rooms[0].length==0)
        return;
 
    int m = rooms.length;
    int n = rooms[0].length;
 
    boolean[][] visited = new boolean[m][n];
 
    for(int i=0; i<m; i++){
        for(int j=0; j<n; j++){
            if(rooms[i][j]==0){
                fill(rooms, i-1, j, 0, visited);
                fill(rooms, i, j+1, 0, visited);
                fill(rooms, i+1, j, 0, visited);
                fill(rooms, i, j-1, 0, visited);
                visited = new boolean[m][n];
            }
        }
    }
}
 
public void fill(int[][] rooms, int i, int j, int start, boolean[][] visited){
    int m=rooms.length;
    int n=rooms[0].length;
 
    if(i<0||i>=m||j<0||j>=n||rooms[i][j]<=0||visited[i][j]){
        return;
    }
 
    rooms[i][j] = Math.min(rooms[i][j], start+1);
    visited[i][j]=true;
 
    fill(rooms, i-1, j, start+1, visited);
    fill(rooms, i, j+1, start+1, visited);
    fill(rooms, i+1, j, start+1, visited);
    fill(rooms, i, j-1, start+1, visited);
 
    visited[i][j]=false;
}

Java: DFS

public void wallsAndGates(int[][] rooms) {
    if(rooms==null || rooms.length==0||rooms[0].length==0)
        return;
 
    int m = rooms.length;
    int n = rooms[0].length;
 
    for(int i=0; i<m; i++){
        for(int j=0; j<n; j++){
            if(rooms[i][j]==0){
                fill(rooms, i, j, 0);
            }
        }
    }
}
 
public void fill(int[][] rooms, int i, int j, int distance){
    int m=rooms.length;
    int n=rooms[0].length;
 
    if(i<0||i>=m||j<0||j>=n||rooms[i][j]<distance){
        return;
    }
 
    rooms[i][j] = distance;
 
    fill(rooms, i-1, j, distance+1);
    fill(rooms, i, j+1, distance+1);
    fill(rooms, i+1, j, distance+1);
    fill(rooms, i, j-1, distance+1);
} 

Java: BFS

public void wallsAndGates(int[][] rooms) {
    if(rooms==null || rooms.length==0||rooms[0].length==0)
        return;
 
    int m = rooms.length;
    int n = rooms[0].length;
 
    LinkedList<Integer> queue = new LinkedList<Integer>();
 
    for(int i=0; i<m; i++){
        for(int j=0; j<n; j++){
            if(rooms[i][j]==0){
                queue.add(i*n+j);
            }
        }
    }
 
    while(!queue.isEmpty()){
        int head = queue.poll();
        int x=head/n;
        int y=head%n;
 
        if(x>0 && rooms[x-1][y]==Integer.MAX_VALUE){
            rooms[x-1][y]=rooms[x][y]+1;
            queue.add((x-1)*n+y);
        }
 
        if(x<m-1 && rooms[x+1][y]==Integer.MAX_VALUE){
            rooms[x+1][y]=rooms[x][y]+1;
            queue.add((x+1)*n+y);
        }
 
        if(y>0 && rooms[x][y-1]==Integer.MAX_VALUE){
            rooms[x][y-1]=rooms[x][y]+1;
            queue.add(x*n+y-1);
        }
 
        if(y<n-1 && rooms[x][y+1]==Integer.MAX_VALUE){
            rooms[x][y+1]=rooms[x][y]+1;
            queue.add(x*n+y+1);
        }
    }
}  

Python:

# Time:  O(m * n)
# Space: O(g)

from collections import deque

class Solution(object):
    def wallsAndGates(self, rooms):
        """
        :type rooms: List[List[int]]
        :rtype: void Do not return anything, modify rooms in-place instead.
        """
        INF = 2147483647
        q = deque([(i, j) for i, row in enumerate(rooms) for j, r in enumerate(row) if not r])
        while q:
            (i, j) = q.popleft()
            for I, J in (i+1, j), (i-1, j), (i, j+1), (i, j-1):
                if 0 <= I < len(rooms) and 0 <= J < len(rooms[0]) and \
                   rooms[I][J] == INF:
                    rooms[I][J] = rooms[i][j] + 1
                    q.append((I, J)) 

C++: DFS

class Solution {
public:
    void wallsAndGates(vector<vector<int>>& rooms) {
        for (int i = 0; i < rooms.size(); ++i) {
            for (int j = 0; j < rooms[i].size(); ++j) {
                if (rooms[i][j] == 0) {
                    dfs(rooms, i + 1, j, 1);
                    dfs(rooms, i - 1, j, 1);
                    dfs(rooms, i, j + 1, 1);
                    dfs(rooms, i, j - 1, 1);
                }
            }
        }
    }
    void dfs(vector<vector<int>> &rooms, int i, int j, int val) {
        if (i < 0 || i >= rooms.size() || j < 0 || j >= rooms[i].size()) return;
        if (rooms[i][j] > val) {
            rooms[i][j] = val;
            dfs(rooms, i + 1, j, val + 1);
            dfs(rooms, i - 1, j, val + 1);
            dfs(rooms, i, j + 1, val + 1);
            dfs(rooms, i, j - 1, val + 1);
        }
    }
};

C++: DFS II

class Solution {
public:
    void wallsAndGates(vector<vector<int>>& rooms) {
        for (int i = 0; i < rooms.size(); ++i) {
            for (int j = 0; j < rooms[i].size(); ++j) {
                if (rooms[i][j] == 0) {
                    dfs(rooms, i, j, 0);
                }
            }
        }
    }
    void dfs(vector<vector<int>> &rooms, int i, int j, int val) {
        if (i < 0 || i >= rooms.size() || j < 0 || j >= rooms[i].size() || rooms[i][j] < val) return;
        rooms[i][j] = val;
        dfs(rooms, i + 1, j, val + 1);
        dfs(rooms, i - 1, j, val + 1);
        dfs(rooms, i, j + 1, val + 1);
        dfs(rooms, i, j - 1, val + 1);
    }
};

  

C++: BFS

class Solution {
public:
    void wallsAndGates(vector<vector<int>>& rooms) {
        queue<pair<int, int>> q;
        vector<vector<int>> dirs{{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
        for (int i = 0; i < rooms.size(); ++i) {
            for (int j = 0; j < rooms[i].size(); ++j) {
                if (rooms[i][j] == 0) q.push({i, j});   
            }
        }
        while (!q.empty()) {
            int i = q.front().first, j = q.front().second; q.pop();
            for (int k = 0; k < dirs.size(); ++k) {
                int x = i + dirs[k][0], y = j + dirs[k][1];
                if (x < 0 || x >= rooms.size() || y < 0 || y >= rooms[0].size() || rooms[x][y] < rooms[i][j] + 1) continue;
                rooms[x][y] = rooms[i][j] + 1;
                q.push({x, y});
            }
        }
    }
};

 

类似题目:

[LeetCode] 317. Shortest Distance from All Buildings 建筑物的最短距离

 

All LeetCode Questions List 题目汇总

 

  

 

 

 

 

 

 

posted @ 2018-02-27 03:29  轻风舞动  阅读(1116)  评论(0编辑  收藏  举报