標籤:
原題連結在這裡: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 value 231 - 1 = 2147483647 to represent INF 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 INFINF INF INF -1INF -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 public class Solution { 2 public void wallsAndGates(int[][] rooms) { 3 if(rooms == null || rooms.length == 0 || rooms[0].length == 0){ 4 return; 5 } 6 int [][] fourDire = {{0,1},{0,-1},{1,0},{-1,0}}; 7 LinkedList<int []> que = new LinkedList<int []>(); 8 9 for(int i = 0; i<rooms.length; i++){10 for(int j = 0; j<rooms[0].length; j++){11 if(rooms[i][j] == 0){12 que.add(new int[]{i,j});13 }14 }15 }16 17 while(!que.isEmpty()){18 int [] gate = que.poll();19 int x = gate[0];20 int y = gate[1];21 for(int k = 0; k<4; k++){22 int newX = x + fourDire[k][0];23 int newY = y + fourDire[k][1];24 if(newX>=0 && newX<rooms.length && newY>=0 && newY<rooms[0].length){25 if(rooms[newX][newY] == Integer.MAX_VALUE){26 rooms[newX][newY] = rooms[x][y] + 1;27 que.add(new int[]{newX, newY});28 }29 }30 }31 }32 }33 }
LeetCode Walls and Gates