高级农民
- 积分
- 1054
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2012-6-12
- 最后登录
- 1970-1-1
|
317. Shortest Distance from All Buildings
从每一个1的位置开始bfs,计算到每个0的距离。
AC的时间位于两个驼峰之间。。。不知道前面的AC是怎么写的。待研究 4/21
- class Solution {
-
- private int[] dx = { 0, -1, 0, 1 };
- private int[] dy = { 1, 0, -1, 0 };
-
- public int shortestDistance(int[][] grid) {
- int row = grid.length, col = grid[0].length;
- int[][] count = new int[row][col];
-
- ArrayList<Integer> buildx = new ArrayList<>();
- ArrayList<Integer> buildy = new ArrayList<>();
- for(int i = 0; i < row; i++){
- for(int j = 0; j < col; j++){
- if(grid[i][j] == 1){
- buildx.add(i);
- buildy.add(j);
- }
- if(grid[i][j] != 0){
- count[i][j] = -1;
- }
- }
- }
-
- for(int i = 0; i < buildx.size(); i++){
- bfs(grid, count, buildx.get(i), buildy.get(i));
- }
-
- int res = Integer.MAX_VALUE;
- for(int i = 0; i < row; i++){
- for(int j = 0; j < col; j++){
- if(count[i][j] != - 1){
- res = Math.min(res, count[i][j]);
- }
- }
- }
- return res == Integer.MAX_VALUE ? -1 : res;
- }
-
- // (m,n) is 1
- private void bfs(int[][] grid, int[][] count, int m, int n){
- Queue<Integer> x = new LinkedList<>();
- Queue<Integer> y = new LinkedList<>();
-
- int row = grid.length, col = grid[0].length, steps = 0;
- int[][] distance = new int[row][col];
- distance[m][n] = -1;
- for(int i = 0; i < 4; i++){
- x.offer(m + dx[i]);
- y.offer(n + dy[i]);
- }
-
- while(x.size() > 0){
- int size = x.size();
- steps += 1;
- for(int i = 0; i < size; i++){
- int px = x.poll();
- int py = y.poll();
- if(px < 0 || px >= row || py < 0 || py >= col || distance[px][py] != 0 || count[px][py] == -1) continue;
- if(grid[px][py] != 0) {
- distance[px][py] = -1;
- continue;
- }
- distance[px][py] = steps;
- for(int j = 0; j < 4; j++){
- x.offer(px + dx[j]);
- y.offer(py + dy[j]);
- }
- }
- }
-
- for(int i = 0; i < row; i++){
- for(int j = 0; j < col; j++){
- if(count[i][j] != -1){
- if(distance[i][j] <= 0){
- count[i][j] = -1;
- }else{
- count[i][j] += distance[i][j];
- }
- }
- }
- }
-
- }
- }
复制代码 |
|