标签:count 01 Matrix int dst 542 ++ depth &&
题目
https://leetcode.com/problems/01-matrix/
题解
这题很有趣,图解一下思路吧~
可以想象成“感染”的过程。
从 1 开始逐层向外扩散,感染的数字 depth 每轮 +1,直到所有格子全部感染为止。
为了避免重复路径,每次判断即将感染的格子是否大于当前的感染数字 depth。
class Solution {
int M;
int N;
public int[][] updateMatrix(int[][] mat) {
int count = 0;
M = mat.length;
N = mat[0].length;
int[][] dst = new int[M][N]; // distance
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (mat[i][j] == 0) {
dst[i][j] = 0;
count++;
} else {
dst[i][j] = Integer.MAX_VALUE;
}
}
}
int depth = 0;
while (count != M * N) {
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (dst[i][j] == depth) {
if (i > 0 && depth + 1 < dst[i - 1][j]) { // left
dst[i - 1][j] = depth + 1;
count++;
}
if (i < M - 1 && depth + 1 < dst[i + 1][j]) { // right
dst[i + 1][j] = depth + 1;
count++;
}
if (j > 0 && depth + 1 < dst[i][j - 1]) { // up
dst[i][j - 1] = depth + 1;
count++;
}
if (j < N - 1 && depth + 1 < dst[i][j + 1]) { // down
dst[i][j + 1] = depth + 1;
count++;
}
}
}
}
depth++;
}
return dst;
}
}
标签:count,01,Matrix,int,dst,542,++,depth,&& 来源: https://blog.csdn.net/sinat_42483341/article/details/119249147
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。