日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

leetcode 542. 01 Matrix | 542. 01 矩阵(图解,广度优先搜索)

發(fā)布時(shí)間:2024/2/28 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。