286 Walls and Gates *** 注意感受DFS
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 than 2147483647.
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.
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
class Solution {
public void wallsAndGates(int[][] rooms) {
int INF = 2147483647;
if (rooms == null || rooms.length == 0 || rooms[0].length == 0) {
return;
}
int rows = rooms.length;
int cols = rooms[0].length;
Queue<Cell> queue = new LinkedList<>();
for (int i = 0; i < rooms.length; i++) {
for(int j = 0; j < rooms[0].length; j++) {
if(rooms[i][j] == 0) {
queue.offer(new Cell(i, j , 0));
}
}
}
int[] dx = {0, 0, 1, -1};
int[] dy = {-1, 1, 0, 0};
while (!queue.isEmpty()) {
int size = queue.size();
for (int j = 0; j < size; j++) {
Cell head = queue.poll();
for (int i = 0; i < 4; i++) {
int newX = head.x + dx[i];
int newY = head.y + dy[i];
if (newX < 0 || newX >= rows || newY < 0 || newY >= cols|| rooms[newX][newY] == -1 ||rooms[newX][newY] == 0) {
continue;
}
if (rooms[newX][newY] == INF) {
Cell newCell = new Cell(newX, newY, head.level + 1);
rooms[newX][newY] = head.level + 1;
queue.offer(newCell);
}
}
}
}
}
class Cell {
int x;
int y;
int level;
public Cell (int xx, int yy, int level) {
this.x = xx;
this.y = yy;
this.level = level;
}
}
}
DFS
class Solution {
public void wallsAndGates(int[][] rooms) {
if (rooms == null || rooms.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) {
dfs(rooms, i, j, 0);
}
}
}
}
public void dfs(int[][] rooms, int x, int y, int level) {
if (x < 0 || x >= rooms.length || y < 0 || y >= rooms[0].length || rooms[x][y] < level) {
return;
}
rooms[x][y] = level;
dfs(rooms, x + 1, y, level + 1);
dfs(rooms, x - 1, y, level + 1);
dfs(rooms, x, y + 1, level + 1);
dfs(rooms, x, y - 1, level + 1);
}
}