码迷,mamicode.com
首页 > 其他好文 > 详细

542. 01 Matrix

时间:2017-10-24 14:52:03      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:direct   位置   忽略   output   out   es2017   res   matrix   变换   

Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.

Example 1: 
Input:

0 0 0
0 1 0
0 0 0

Output:

0 0 0
0 1 0
0 0 0

 

Example 2: 
Input:

0 0 0
0 1 0
1 1 1

Output:

0 0 0
0 1 0
1 2 1

Note:

  1. The number of elements of the given matrix will not exceed 10,000.
  2. There are at least one 0 in the given matrix.
  3. The cells are adjacent in only four directions: up, down, left and right.

题目含义:给定一个只含0和1的矩阵,找到每个1到0的最短距离。 两个相邻单元格的距离是1 

思路:

  1. 对待求矩阵进行一次变换,遇0元素不变,遇1元素设为最大值。 
    技术分享

     

inf在此处表示无穷,在Java代码中,用Integer.MAX_VALUE来表示。在对它变换的同时,由于已经扫描了一遍矩阵,在此过程中还需要记录所有0元素的row,col值,并放入一个队列中。

接下来是求解的核心了,我们只需要寻找到一种机制能够准确更新该数组就可以了,并且它的更新规则符合题意。刚才的dfs是在一个方向上遍历到底,没法拐弯,问题的关键在于隔壁的1元素是否携带了有效信息供当前节点参考!很明显,dfs方案一条路走到底,每个1元素忽略另外三个方向的信息,所以自然而然无法求出正确的。

而再来看看bfs,用形象的比喻来描述这道题的话,就是一颗石头扔入湖中时,它的影响波及周围,且向四周不断传播它的影响。所以该算法的思想,就是首先把这些石头找出来咯【0元素】,更新规则是,一旦碰到【inf】,我就设一个该【0元素】对【inf】的影响值,此处为1。但由于【0元素】的影响是传递的,所以受它影响的【inf】节点必须得放入队列中,计算下次影响值。碰到【inf】,则+1,但前提是当前【inf】节点的值大于原先的值+1。

第二次更新: 

技术分享

 

 

0元素周围的元素均被波及,接下来就是1元素的传递,传递的还是0元素的影响。

第三次更新: 

技术分享

 

 1     public int[][] updateMatrix(int[][] matrix) {
 2 //    一定要看此地址,否则很那理解       http://blog.csdn.net/u014688145/article/details/64126559
 3         int m = matrix.length;
 4         int n = matrix[0].length;
 5         Queue<int[]> q = new LinkedList<>();
 6         for (int i = 0; i < m; i++) {
 7             for (int j = 0; j < n; j++) {
 8                 if (matrix[i][j] == 0) q.add(new int[]{i, j}); //把0元素加入队列中,以备波及影响周围元素
 9                 else matrix[i][j] = Integer.MAX_VALUE;//设为最大值,方便求0元素影响值
10             }
11         }
12         //溅起的涟漪,代表传播的四个方向
13         int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
14         while (!q.isEmpty()) {
15             int[] cell = q.poll();
16             for (int[] dirc : dirs) {
17                 //需要比较的下一位置元素
18                 int r = cell[0] + dirc[0];
19                 int c = cell[1] + dirc[1];
20 
21                 //如果下一位置的元素值,小于等于(当前位置元素值+1),直接跳过
22                 if (r < 0 || r >= m || c < 0 || c >= n || matrix[r][c] <= (matrix[cell[0]][cell[1]] + 1)) continue;
23                 else {
24                     matrix[r][c] = matrix[cell[0]][cell[1]] + 1;
25                     q.offer(new int[]{r, c});
26                 }
27             }
28         }
29         return matrix;        
30     }

 

542. 01 Matrix

标签:direct   位置   忽略   output   out   es2017   res   matrix   变换   

原文地址:http://www.cnblogs.com/wzj4858/p/7723330.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!