LeetCode 286. Walls and Gates
原题链接在这里:https://leetcode.com/problems/walls-and-gates/
题目:
You are given a m x n 2D grid initialized with these three possible values.
-1
- A wall or an obstacle.0
- A gate.INF
- Infinity means an empty room. We use the value231 - 1 = 2147483647
to representINF
as you may assume that the distance to a gate is less than2147483647
.
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
题解:
BFS, 先把所有gate加到que中。对于每一个从que中poll出来的gate,看四个方向是否有room, 若有,把room的值改正gate + 1, 在放回到que中.
Time Complexity: O(m*n). m = rooms.length, n = rooms[0].length. 每个点没有扫描超过两遍. Space: O(m*n).
AC Java:
1 class Solution { 2 public void wallsAndGates(int[][] rooms) { 3 if(rooms == null || rooms.length == 0 || rooms[0].length == 0){ 4 return; 5 } 6 7 int m = rooms.length; 8 int n = rooms[0].length; 9 LinkedList<int []> que = new LinkedList<>(); 10 int level = 1; 11 for(int i = 0; i < m; i++){ 12 for(int j = 0; j < n; j++){ 13 if(rooms[i][j] == 0){ 14 que.add(new int[]{i, j}); 15 } 16 } 17 } 18 19 int [][] dirs = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; 20 21 while(!que.isEmpty()){ 22 int size = que.size(); 23 while(size-- > 0){ 24 int [] cur = que.poll(); 25 for(int [] dir : dirs){ 26 int x = cur[0] + dir[0]; 27 int y = cur[1] + dir[1]; 28 if(x < 0 || x >= m || y < 0 || y >= n || rooms[x][y] != Integer.MAX_VALUE){ 29 continue; 30 } 31 32 que.add(new int[]{x, y}); 33 rooms[x][y] = level; 34 } 35 } 36 37 level++; 38 } 39 } 40 }
跟上Robot Room Cleaner, Rotting Oranges, Shortest Distance from All Buildings.