美文网首页
[LeetCode 286] Walls and Gates (

[LeetCode 286] Walls and Gates (

作者: 灰睛眼蓝 | 来源:发表于2019-05-20 16:36 被阅读0次

    Solution

    1. 从每个gate出发,对其上下左右的INF用DFS求其distance深度。
    2. 起始distance == 0, 每进一次,distance + 1
    3. base case 1: row & col Out of Bound
    4. base case2: 保证是最小的distance,且避开gate 和 wall。
    // ensure the min distance, and avoid wall and gate as well because distance is start from 1, wall value is -1, gate is 0
    if (rooms [row][col] < distance)
        return;
    

    代码

    class Solution {
        public void wallsAndGates(int[][] rooms) {
            if (rooms == null || rooms.length == 0 || rooms [0].length == 0)
                return;
            
            for (int i = 0; i < rooms.length; i++) {
                for (int j = 0; j < rooms[0].length; j++) {
                    if (rooms [i][j] == 0) {
                        wallsAndGatesHelper (rooms, i, j, 0);  //distance from gate to INF
                    }
                }
            }
        }
        
        public void wallsAndGatesHelper (int[][] rooms, int row, int col, int distance) {
            // out of bound
            if (row < 0 || row >= rooms.length || col < 0 || col >= rooms[0].length)
                return;
            // ensure the min distance, and avoid wall and gate as well because distance is start from 1, wall value is -1, gate is 0
            if (rooms [row][col] < distance)
                return;
            
            int[][] directions = {{1, 0},{0, 1},{-1, 0},{0, -1}};
            rooms [row][col] = distance;
            
            for (int[] direction : directions) {
                wallsAndGatesHelper (rooms, row + direction [0], col + direction [1], distance + 1);
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:[LeetCode 286] Walls and Gates (

          本文链接:https://www.haomeiwen.com/subject/mbokzqtx.html