您的位置:首页 > 其它

542. 01 Matrix [LeetCode]

2017-07-21 22:50 615 查看
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:

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

题目大意:这题给我们一个0-1矩阵,要我们求出矩阵中每个元素,到最近的0的距离。

思路概述:因为0元素最后的返回值还是0,要求元素1到最近的0的距离,首先就想到BFS。首先,我从每一个1开始向周围BFS,直到找到最近的0,但这样做的时间复杂度过高,提交结果TLE,没有能够通过。
之后在LeetCode的讨论区学习了一下,发现思路没有什么问题,只是BFS遍历时可以优化一下:遍历原数组,将1都置为Max_Value。建立一个队列,加入所有0元素的位置;之后从队列中的元素出发遍历周边元素,如果其周边的元素不越界且大于元素值+1,更新其值为当前中心元素值+1,将这个周边元素加到队列中,构成下一层节点。

AC代码如下:

public class Solution {
public int[][] updateMatrix(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;

if (m==0 || n==0 || matrix==null)
return null;

Queue<int[]> queue = new LinkedList<>();
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
if (matrix[i][j] == 0) {
queue.offer(new int[] {i, j});
} else {
matrix[i][j] = Integer.MAX_VALUE;
}
}
}

int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
while (!queue.isEmpty()) {
int[] cell = queue.poll();
for (int[] dir : dirs) {
int x = cell[0] + dir[0];
int y = cell[1] + dir[1];
if (x<0 || x>=m || y<0 || y>=n || matrix[x][y] <= matrix[cell[0]][cell[1]]+1)
continue;
queue.offer(new int[] {x, y});
matrix[x][y] = matrix[cell[0]][cell[1]] + 1;
}
}

return matrix;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode