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

[LeetCode] 542. 01 Matrix

时间:2020-04-16 13:25:54      阅读:47      评论:0      收藏:0      [点我收藏+]

标签:div   cas   inpu   mat   ++   dir   integer   length   put   

01矩阵。题意是给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。两个相邻元素间的距离为 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]]

因为是找matrix里面的最短距离,所以思路是BFS。首先将所有值为0的元素都加入queue,再将所有不为0的元素全都标记成Integer.MAX_VALUE。然后按照BFS的正常思路遍历queue中的每个点。在扫描每个点的时候,如果超出input边界,或者这个点和他自己四个邻居点之间的差值小于等于1的时候则直接跳过,理由是因为两个点之间最短的距离也只可能是1。跳过了这些case之后,再被加入queue的应该只有可能是一开始被标记成Integer.MAX_VALUE的坐标值了。如果这些点在某一次扫描中被发现了,他们就会被标记成1然后再次放入queue。

这个做法巧妙的地方在于先将值为1的坐标改成Integer.MAX_VALUE,这样越靠近0的点会被越先改成1。被改成1的坐标旁边如果还有Integer.MAX_VALUE,会在被找到之后再被赋值为1 + 1 = 2。参考第二个例子。

时间O(mn)

空间O(mn) - worse case可能所有元素都要经过一遍queue

Java实现

 1 class Solution {
 2     public int[][] updateMatrix(int[][] matrix) {
 3         int m = matrix.length;
 4         int n = matrix[0].length;
 5         Queue<int[]> queue = new LinkedList<>();
 6         for (int i = 0; i < m; i++) {
 7             for (int j = 0; j < n; j++) {
 8                 if (matrix[i][j] == 0) {
 9                     queue.offer(new int[] { i, j });
10                 } else {
11                     matrix[i][j] = Integer.MAX_VALUE;
12                 }
13             }
14         }
15         int[][] dirs = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
16         while (!queue.isEmpty()) {
17             int[] point = queue.poll();
18             for (int[] dir : dirs) {
19                 int row = point[0] + dir[0];
20                 int col = point[1] + dir[1];
21                 if (row < 0 || row >= m || col < 0 || col >= n || matrix[row][col] <= matrix[point[0]][point[1]] + 1) {
22                     continue;
23                 }
24                 queue.offer(new int[] { row, col });
25                 matrix[row][col] = matrix[point[0]][point[1]] + 1;
26             }
27         }
28         return matrix;
29     }
30 }

 

[LeetCode] 542. 01 Matrix

标签:div   cas   inpu   mat   ++   dir   integer   length   put   

原文地址:https://www.cnblogs.com/aaronliu1991/p/12711849.html

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