leetcode 286: Walls and Gates
来源:互联网 发布:淘宝店铺号搜不到 编辑:程序博客网 时间:2024/05/22 09:04
Walls and Gates
Total Accepted: 411 Total Submissions: 1365 Difficulty: Medium
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 withINF
.
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
[思路]
注意剪枝, 注意overflow
[CODE]
public class Solution { public void wallsAndGates(int[][] rooms) { if(rooms==null || rooms.length==0 || rooms[0]==null || rooms[0].length==0) return; int m = rooms.length; int n =rooms[0].length; boolean[][] visited = new boolean[m][n]; for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { if(rooms[i][j] == Integer.MAX_VALUE) { rooms[i][j] = search(rooms, visited, i, j, m, n); } } } return; } private int search(int[][] rooms, boolean[][] visited, int i, int j, int m, int n) { if(i<0 || i>m-1 || j<0 || j>n-1 || rooms[i][j] == -1) return Integer.MAX_VALUE; if(rooms[i][j]==0) return 0; if(visited[i][j]) return rooms[i][j]; visited[i][j] = true; if(rooms[i][j]>0 && rooms[i][j]<Integer.MAX_VALUE) return rooms[i][j]; int up = search(rooms, visited, i-1, j, m, n); int down = search(rooms, visited, i+1, j, m, n); int left = search(rooms, visited, i, j-1, m, n); int right = search(rooms, visited, i, j+1, m, n); visited[i][j] = false; int min = Math.min( Math.min(up, down), Math.min(left, right) ); return min==Integer.MAX_VALUE ? min : min+1; } }
0 0
- leetcode 286: Walls and Gates
- [Leetcode 286]: Walls and Gates
- *LeetCode-Walls and Gates
- Leetcode: Walls and Gates
- 286 Walls and Gates
- Leetcode 286.Walls and Gates
- LeetCode 286. Walls and Gates
- Leetcode 286. Walls and Gates
- LeetCode 286. Walls and Gates
- [leetcode 286] Walls and Gates---各个点到门的距离
- LeetCode 题解(259) : Walls and Gates
- [leetcode] 286. Walls and Gates 解题报告
- [Leetcode] 286. Walls and Gates 解题报告
- [LeetCode286]Walls and Gates
- Walls and Gates
- Walls and Gates
- Walls and Gates
- Walls and Gates
- Python已安装第三方库
- Basic Calculator
- SVM 要点回顾
- PHP优化:APC缓存+mysql
- 对象与内存的关系
- leetcode 286: Walls and Gates
- java 小数转换成百分比显示
- 牛客学堂第四节
- C#高亮关键字
- 封装概念
- 如何用SED批量 查找、添加、删除、替换配置文件里面的选项
- 构造方法
- 关于String的解析
- Android自定义View,你必须知道的几点