这道题用dfs妥妥的超时,和路径有关的bfs,必须按层次遍历,只要遍历到结果了,直接返回,一定是最优解。8个方向可以用二维数组来存。切记要将访问过的标记一下, 这里用1标记即可
class Solution {
public:
int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
//这里肯定bfs更方便,只要走到结果了,一定就是最优解,dfs的话要递归出所有结果才可以进行比较,bfs用queue
//q中存的是坐标
queue<pair<int,int>> q;
if(grid[0][0] == 1) return -1;
q.push(make_pair(0,0));
//bfs一定要注意不能重复走,把走过的点设为1就行了,一定不会再走
int step = 1;
int n = grid.size();
vector<vector<int>> dir = {
{
0,1},{
0,-1},{
1,0},{
-1,0},{
1,1},{
1,-1},{
-1,-1},{
-1,1}};
while(!q.empty()){
int sz = q.size();
while(sz-- != 0){
int row = q.front().first;
int col = q.front().second;
q.pop();
if(row == n-1 && col == n-1) return step;
for(int i = 0; i < 8; ++i){
int row1 = row +dir[i][0];
int col1 = col +dir[i][1];
if(row1 <0 || row1 >= n || col1<0||col1 >= n||grid[row1][col1] == 1)
continue;
grid[row1][col1] = 1;
q.push(make_pair(row1,col1));
}
}
step++;
}
return -1;
}
};