[Leetcode] 01 Matrix

问题: https://leetcode.com/problems/01-matrix/#/description

基本思路:广度优先遍历,根据所有最短距离为N的格找到所有距离为N+1的格,直到所有的格都找到了最短距离。

具体步骤:

首先初始化矩阵,值为0的格其最短距离也是0,保持不变;值为1的格是后面需要计算最短距离的格,我们需要一个整数来标识它们,这里可以选择一个负数或者整数的最大值。

然后进行若干轮计算,第N轮会根据已经计算出的最短距离为N-1的所有格,来找出所有最短距离为N的格。

例如,第1轮计算就是根据所有最短距离为0的格,找到所有距离为1的格。

第5轮计算,就是根据所有最短距离为4的格,找到所有距离为5的格。

具体怎么找呢?对每一个最短距离为N-1的格,跟它相邻的上下左右四个方向的格,其中还没有计算出最短距离的格(即值为负数或者整数的最大值的)的最短距离一定是N。

如果不是N而是小于N的某个数M的话,那么这个格在前面的M-1轮就应该找到了,跟第M-1轮找到所有的最短距离为M的格矛盾。

用Java 8实现如下:

 1 public class Solution {
 2     public int[][] updateMatrix(int[][] matrix) {
 3         Queue<int[]> queue = new LinkedList<>();
 4         // 初始化矩阵
 5         for(int i = 0; i < matrix.length; i++) {
 6             for(int j = 0; j < matrix[0].length; j++) {
 7                 if(matrix[i][j] == 0) {
 8                     queue.offer(new int[]{i, j});
 9                 }else {
10                     matrix[i][j] = Integer.MAX_VALUE;
11                 }
12             }
13         }
14         
15         int[][] dirs = new int[][]{{0, -1},{-1, 0},{0, 1},{1, 0}};
16         while(!queue.isEmpty()) {
17             int[] cell = queue.poll();
18             for(int i = 0; i < dirs.length; i++) {
19                 int r = cell[0] + dirs[i][0];
20                 int c = cell[1] + dirs[i][1];
21                 if(r >= 0 && r < matrix.length && c >= 0 && c < matrix[0].length && matrix[cell[0]][cell[1]] + 1 < matrix[r][c]) {
22                     matrix[r][c] = matrix[cell[0]][cell[1]] + 1;
23                     queue.offer(new int[]{r, c});
24                 }
25             }
26         }
27         
28         return matrix;
29     }
30 }

 

posted @ 2017-04-25 01:10  爪哇国臣民  阅读(447)  评论(0编辑  收藏  举报