给定一个由 0 和 1 组成的矩阵,找出每一个元素到最近的 0 的距离。java
两个相邻元素间的距离为 1 。node
Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.python
The distance between two adjacent cells is 1.数组
示例 1: 输入:bash
0 0 0
0 1 0
0 0 0
复制代码
输出:app
0 0 0
0 1 0
0 0 0
复制代码
示例 2: 输入:spa
0 0 0
0 1 0
1 1 1
复制代码
输出:rest
0 0 0
0 1 0
1 2 1
复制代码
注意:code
Note:cdn
关键字:最近、距离。那确定是广度优先搜索。相似以前的文章 岛屿数量: mp.weixin.qq.com/s/BrlMzXTtZ…
将这个问题转化成图,那就是求每一个节点 1 到节点 0 最短的路径是多少。从某个节点开始,上下左右向外扩展,每次扩展一圈距离累加1,如:
输入:
1 1 1
0 1 0
0 0 0
复制代码
转化成图(Graph),每种颜色表明一个层级:
这就变成了求某个节点到某个节点的深度了。
因此这道题有两种思路:
两种方法各有优劣,
以0节点为根节点解题,要么开辟一个新的二维数组以记录路径,要么先遍历一遍将全部的节点1的值改成不可能和路径大小重复的值。
以1节点为根节点,那么就要作一些多余的重复遍历。
逻辑顺序:
以输入下列二维数组为例:
1 1 1
0 1 1
0 0 1
复制代码
先把原节点值为1 的节点改成M (路径值不可能达到的值,该题中大于10000便可)
先侵染0节点附近的M节点,0节点加1以后获得1节点
再侵染1节点附近的M节点,1节点加1以后获得2节点
......
Java:
class Solution {
public int[][] updateMatrix(int[][] matrix) {
int row = matrix.length, column = matrix[0].length;
int[][] neighbors = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};//邻居节点的索引偏移量
Queue<int[]> queue = new LinkedList<>();//队列
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if (matrix[i][j] == 0) queue.offer(new int[]{i, j});
else matrix[i][j] = Integer.MAX_VALUE;//节点值为1的节点改成一个路径不可能达到的值
}
}
while (!queue.isEmpty()) {
int[] tmp = queue.poll();
for (int i = 0; i < 4; i++) {
//获得邻居节点索引
int x = tmp[0] + neighbors[i][0];
int y = tmp[1] + neighbors[i][1];
if (x >= 0 && x < row && y >= 0 && y < column && matrix[tmp[0]][tmp[1]] < matrix[x][y]) {
matrix[x][y] = matrix[tmp[0]][tmp[1]] + 1;//该节点的值获得邻居节点的路径值+1
queue.offer(new int[]{x, y});
}
}
}
return matrix;
}
}
复制代码
Python3:
class Solution:
def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
row, column = len(matrix), len(matrix[0])
nerghbors = [(0, 1), (0, -1), (1, 0), (-1, 0)]
queue = collections.deque()
for i in range(row):
for j in range(column):
if matrix[i][j] == 0:
queue.append((i, j))
else:
matrix[i][j] = 10001
while queue:
x, y = queue.popleft()
for i, j in nerghbors:
xx = i + x
yy = j + y
if 0 <= xx < row and 0 <= yy < column and matrix[x][y] < matrix[xx][yy]:
matrix[xx][yy] = matrix[x][y] + 1
queue.append((xx, yy))
return matrix
复制代码
Java:
class Solution {
public int[][] updateMatrix(int[][] matrix) {
int row = matrix.length, column = matrix[0].length;
for (int i = 0; i < row; i++)
for (int j = 0; j < column; j++)
if (matrix[i][j] == 1) matrix[i][j] = bfs(matrix, i, j, row, column);
return matrix;
}
private int bfs(int[][] matrix, int i, int j, int row, int column) {
int count = 0;
Queue<Integer> queue = new LinkedList<>();
Set<int[]> set = new HashSet<>();
queue.add(i * column + j);//记录索引的另外一种方法
while (!queue.isEmpty()) {
int size = queue.size();
count += 1;
for (int k = 0; k < size; k++) {
int tmp = queue.poll();
int x = tmp / column, y = tmp % column;//获得索引坐标
//处理上下左右四个邻居节点,遇到0节点直接返回count路径值
if (x + 1 < row && !set.contains((x + 1) * column + y)) {
if (matrix[x + 1][y] != 0) queue.add((x + 1) * column + y);
else return count;
}
if (x - 1 >= 0 && !set.contains((x - 1) * column + y)) {
if (matrix[x - 1][y] != 0) queue.add((x - 1) * column + y);
else return count;
}
if (y + 1 < column && !set.contains(x * column + y + 1)) {
if (matrix[x][y + 1] != 0) queue.add(x * column + y + 1);
else return count;
}
if (y - 1 >= 0 && !set.contains(x * column + y - 1)) {
if (matrix[x][y - 1] != 0) queue.add(x * column + y - 1);
else return count;
}
}
}
return count;
}
}
复制代码
Python3:
class Solution:
def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
row, column = len(matrix), len(matrix[0])
for i in range(row):
for j in range(column):
if matrix[i][j] == 1:
matrix[i][j] = self.bfs(i, j, matrix, row, column)
return matrix
def bfs(self, i: int, j: int, matrix: List[List[int]], row: int, column: int) -> int:
queue = collections.deque()
count = 0
nodeset = set()
queue.append((i, j))
while queue:
size = len(queue)
count += 1
for i in range(size):
x, y = queue.popleft()
if x + 1 < row and (x + 1, y) not in nodeset:
if matrix[x + 1][y] != 0:
queue.append((x + 1, y))
else:
return count
if x - 1 >= 0 and (x - 1, y) not in nodeset:
if matrix[x - 1][y] != 0:
queue.append((x - 1, y))
else:
return count
if y + 1 < column and (x, y + 1) not in nodeset:
if matrix[x][y + 1] != 0:
queue.append((x, y + 1))
else:
return count
if y - 1 >= 0 and (x, y - 1) not in nodeset:
if matrix[x][y - 1] != 0:
queue.append((x, y - 1))
else:
return count
return count
复制代码
欢迎关注微.信公.众号:爱写Bug