Walls and Gates
Posted 北叶青藤
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
Understand the problem:
It is very classic backtracking problem. We can start from each gate (0 point), and searching for its neighbors. We can either use DFS or BFS solution.
1 public class Solution { 2 public void wallsAndGates(int[][] rooms) { 3 if (rooms == null || rooms.length == 0) { 4 return; 5 } 6 7 int m = rooms.length; 8 int n = rooms[0].length; 9 10 boolean[][] visited = new boolean[m][n]; 11 12 for (int i = 0; i < m; i++) { 13 for (int j = 0; j < n; j++) { 14 if (rooms[i][j] == 0) { 15 wallsAndGatesHelper(i, j, 0, visited, rooms); 16 } 17 } 18 } 19 } 20 21 private void wallsAndGatesHelper(int row, int col, int distance, boolean[][] visited, int[][] rooms) { 22 int rows = rooms.length; 23 int cols = rooms[0].length; 24 25 if (row < 0 || row >= rows || col < 0 || col >= cols) { 26 return; 27 } 28 29 // visited 30 if (visited[row][col]) { 31 return; 32 } 33 34 // Is wall? 35 if (rooms[row][col] == -1) { 36 return; 37 } 38 39 // Distance greater than current 40 if (distance > rooms[row][col]) { 41 return; 42 } 43 44 45 // Mark as visited 46 visited[row][col] = true; 47 48 if (distance < rooms[row][col]) { 49 rooms[row][col] = distance; 50 } 51 52 // go up, down, left and right 53 wallsAndGatesHelper(row - 1, col, distance + 1, visited, rooms); 54 wallsAndGatesHelper(row + 1, col, distance + 1, visited, rooms); 55 wallsAndGatesHelper(row, col - 1, distance + 1, visited, rooms); 56 wallsAndGatesHelper(row, col + 1, distance + 1, visited, rooms); 57 58 // Mark as unvisited 59 visited[row][col] = false; 60 } 61 }
From:
http://buttercola.blogspot.com/2015/09/leetcode-walls-and-gates.html
以上是关于Walls and Gates的主要内容,如果未能解决你的问题,请参考以下文章