有什么网站可以免费建站,中国好公司网站建设,需要怎么办,中国互联网公司排名100强思路 BFS
解题过程 从起点依次向八个方向尝试#xff08;之后也一样#xff09;#xff0c;如果某个位置在矩阵内且值为0且没有访问过#xff0c;将其添加到一个队列中#xff0c;依次类推#xff0c;直到到达出口
Code
class Solution {public int shortestPathBinar… 思路 BFS
解题过程 从起点依次向八个方向尝试之后也一样如果某个位置在矩阵内且值为0且没有访问过将其添加到一个队列中依次类推直到到达出口
Code
class Solution {public int shortestPathBinaryMatrix(int[][] grid) {int ans 1;int nn grid.length;int vis[][] new int[nn][nn];vis[0][0] 1;LinkedListint[] q new LinkedList();if (grid[0][0] 1)return -1;q.add(new int[] { 0, 0 });while (!q.isEmpty()) {int len q.size();for (int i 0; i len; i) {int arr[] q.poll();int x arr[0];int y arr[1];if (x nn - 1 y nn - 1)return ans;for (int m x - 1; m x 1; m) {for (int n y - 1; n y 1; n) {if (0 m m nn 0 n n nn vis[m][n] 0 grid[m][n] 0) {grid[m][n] 1;q.offer(new int[] { m, n });}}}}ans;}return -1;}}作者菜卷
链接https://leetcode.cn/problems/shortest-path-in-binary-matrix/solutions/3034582/er-jin-zhi-ju-zhen-zhong-de-zui-duan-lu-xsg22/
来源力扣LeetCode
著作权归作者所有。商业转载请联系作者获得授权非商业转载请注明出处。