赞
踩
解题思路:
使用广度优先遍历的方法,可以遍历下一步能走的位置,一般用到广度优先就离不开队列,队列存储着当前轮次能够走的位置,每一轮都要将能走的长度++,如果队列无元素,说明无处可走,此时没有到终点就直接返回-1,代码中注释已经很详尽了,按照步骤一步一步看肯定可以看懂。关键就在于
class Solution { public: int shortestPathBinaryMatrix(vector<vector<int>>& grid) { // 所给的地图为空 if(grid.size() == 0) { return -1; } // 确定方向 int direction[8][2] = {{1, -1}, {1, 0}, {1, 1}, {0, 1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}}; int m = grid.size(), n = grid[0].size(); // 用队列存储每一轮能够经过的地方 queue<vector<int>> q; // 把第一个点放进去 q.push({0, 0}); int length = 0; // 如果队列不为空,说明还能走,空了说明走不下去了直接返回-1 while(!q.empty()) { // 每一轮步长+1 length ++; int size = q.size(); // 遍历每一轮中能够走到的位置 while(-- size >= 0) { vector<int> site = q.front(); q.pop(); int x = site[0], y = site[1]; // 如果不能走 if(grid[x][y] == 1) { continue; } // 如果走到右下角 if(x == m - 1 && y == n - 1) { return length; } // 走过的位置标记为不能走 grid[x][y] = 1; // 八个方向遍历下一步能走的位置 for(auto d : direction) { int x1 = x + d[0], y1 = y + d[1]; if(x1 < 0 || x1 >= m || y1 < 0 || y1 >= n) { continue; } if(grid[x1][y1] == 1) { continue; } q.push({x1, y1}); } } } return -1; } }; /*作者:heroding 链接:https://leetcode-cn.com/problems/shortest-path-in-binary-matrix/solution/c-bfsdui-lie-by-heroding-biko/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。