算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 01 矩阵,我们先来看题面:
https://leetcode-cn.com/problems/01-matrix/
Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.
给定一个由 0 和 1 组成的矩阵 mat ,请输出一个大小相同的矩阵,其中每一个格子是 mat 中对应位置元素到最近的 0 的距离。
两个相邻元素间的距离为 1 。
示例
解题
使用广度优先搜索需要从0开始,一层一层往外寻找。
我们把全部的0入队,并且把原来的1置为-1(说明没有被访问过),然后出队,如果周围有-1,则距离就是出队的元素的数值+1
class Solution {
public int[][] updateMatrix(int[][] matrix) {
int N = matrix.length;
int M = matrix[0].length;
Deque<int[]> deque = new LinkedList<>();
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (matrix[i][j] == 0) //把所有0入队
deque.offer(new int[]{i, j});
if (matrix[i][j] == 1)
matrix[i][j] = -1; //把1都置为-1,表示没有访问过
}
}
int[] xPos = new int[]{0, 0, 1, -1};
int[] yPos = new int[]{-1, 1, 0, 0};
while (!deque.isEmpty()) {
int[] pos = deque.poll();
for (int i = 0; i < 4; i++) {
int x = pos[0] + xPos[i];
int y = pos[1] + yPos[i];
if (x >= 0 && x < N && y >= 0 && y < M && matrix[x][y] == -1) {
//每个出队元素只访问其上下左右四个方向
matrix[x][y] = matrix[pos[0]][pos[1]] + 1;
deque.offer(new int[]{x, y}); //改变了后入队,检查其上下左右
}
}
}
return matrix;
}
}
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: