[LeetCode]Shortest Distance from All Buildings
2015-12-14 14:02
676 查看
对每个房子bfs,找出每个房子到所有空地的距离。用一个record二维数组来记录每个空地上所有房子到该空地的距离和。同时用另一个二维数组记录每个空地能被几个房子访问到,来保证所有房子都可以到达的了该空地。
public class Solution { public int shortestDistance(int[][] grid) { int row = grid.length; if (row == 0) { return -1; } int col = grid[0].length; int[][] record1 = new int[row][col]; // visited num int[][] record2 = new int[row][col]; // distance int num1 = 0; for (int r = 0; r < row; r++) { for (int c = 0; c < col; c++) { if (grid[r][c] == 1) { num1 ++; boolean[][] visited = new boolean[row][col]; Queue<int[]> queue = new LinkedList<int[]>(); queue.offer(new int[]{r, c}); int dist = 0; while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { int[] node = queue.poll(); int x = node[0]; int y = node[1]; record2[x][y] += dist; record1[x][y] ++; if (x > 0 && grid[x - 1][y] == 0 && !visited[x - 1][y]) { queue.offer(new int[]{x - 1, y}); visited[x - 1][y] = true; } if (x + 1 < row && grid[x + 1][y] == 0 && !visited[x + 1][y]) { queue.offer(new int[]{x + 1, y}); visited[x + 1][y] = true; } if (y > 0 && grid[x][y - 1] == 0 && !visited[x][y - 1]) { queue.offer(new int[]{x, y - 1}); visited[x][y - 1] = true; } if (y + 1 < col && grid[x][y + 1] == 0 && !visited[x][y + 1]) { queue.offer(new int[]{x, y + 1}); visited[x][y + 1] = true; } } dist ++; } } } } int result = Integer.MAX_VALUE; for (int r = 0; r < row; r++) { for (int c = 0; c < col; c++) { if (grid[r][c] == 0 && record1[r][c] == num1 && record2[r][c] < result) { result = record2[r][c]; } } } return result == Integer.MAX_VALUE ? -1 : result; } }
相关文章推荐
- 第二篇:_UICascadingTextStorage attributesAtIndex:effectiveRange:]: Range or index out of bounds
- 各个大神大公司的UED
- [_UICascadingTextStorage attributesAtIndex:effectiveRange:]: Range or index out of bounds
- IOS8 keyboardWillShow 在UIKeyboardWillShowNotification 调用两次 问题解决
- UIButton
- HDU 4915 Parenthese sequence _(:зゝ∠)_ 哈哈
- iOS开发 Xcode UIImageView设置一个圆形的图片
- JAVA中生成C#中的GUID作为主键
- iOS 16进制颜色和UIcolor的转换
- vmware虚拟机guest系统重启后获得169.254.X.X的ip解决方法
- OC NSNumber和NSValue和NSDate和NSData
- 【LEETCODE】225-Implement Stack using Queues
- UIAlertViewController+TextField 输入框
- foundation的使用——NSNumber NSValue
- 【翻译】oc.lazyLoad with Angular ui router(按需加载文件)
- Git GUI下载远程源代码简单使用介绍
- Shiro介绍(六):扩展自己的@RequiresPermission
- 利用WebRequest类上传文件
- [Tue, 1 Dec 2015 ~ Fri, 4 Dec 2015] Deep Learning in arxiv
- UI之slider、segmentControl