LeetCode 286: Walls and Gates
Posted keepshuatishuati
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 286: Walls and Gates相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章