码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 286: Walls and Gates

时间:2017-09-07 14:58:10      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:rom   code   eve   from   color   visit   point   room   ann   

Note:

Need to skipp the 0 element update room but cannot skip BFS from that point

class Solution {
    public void wallsAndGates(int[][] rooms) {
        if (rooms.length == 0 || rooms[0].length == 0) {
            return;
        }
        
        for (int i = 0; i < rooms.length; i++) {
            for (int j = 0; j < rooms[i].length; j++) {
                if (rooms[i][j] == 0) {
                    visit(rooms, i, j, 0);
                }
            }
        }
    }
    
    private void visit(int[][] rooms, int x, int y, int level) {
        if (rooms[x][y] == -1) {
            return;
        }
        
        if (level == 0 || rooms[x][y] > level) {
            if (level != 0) {
                rooms[x][y] = level;
            }
            if (x > 0) visit(rooms, x - 1, y, level + 1);
            if (x < rooms.length - 1) visit(rooms, x + 1, y, level + 1);
            if (y > 0) visit(rooms, x, y - 1, level + 1);
            if (y < rooms[0].length - 1) visit(rooms, x, y + 1, level + 1);
        }
    }
}

 

LeetCode 286: Walls and Gates

标签:rom   code   eve   from   color   visit   point   room   ann   

原文地址:http://www.cnblogs.com/shuashuashua/p/7489312.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!