标签:
-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
.INF
.INF -1 0 INF INF INF INF -1 INF -1 INF -1 0 -1 INF INF
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
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5944468.html