leetcode 542. 01 Matrix | 542. 01 矩阵(图解,广度优先搜索)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 542. 01 Matrix | 542. 01 矩阵(图解,广度优先搜索)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目
https://leetcode.com/problems/01-matrix/
題解
這題很有趣,圖解一下思路吧~
可以想象成“感染”的過(guò)程。
從 1 開(kāi)始逐層向外擴(kuò)散,感染的數(shù)字 depth 每輪 +1,直到所有格子全部感染為止。
為了避免重復(fù)路徑,每次判斷即將感染的格子是否大于當(dāng)前的感染數(shù)字 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]; // distancefor (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]) { // leftdst[i - 1][j] = depth + 1;count++;}if (i < M - 1 && depth + 1 < dst[i + 1][j]) { // rightdst[i + 1][j] = depth + 1;count++;}if (j > 0 && depth + 1 < dst[i][j - 1]) { // updst[i][j - 1] = depth + 1;count++;}if (j < N - 1 && depth + 1 < dst[i][j + 1]) { // downdst[i][j + 1] = depth + 1;count++;}}}}depth++;}return dst;} }總結(jié)
以上是生活随笔為你收集整理的leetcode 542. 01 Matrix | 542. 01 矩阵(图解,广度优先搜索)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: leetcode 399. Evalua
- 下一篇: leetcode 677. Map Su