class Solution {
public:
vector<vector<bool>> visited;
vector<vector<int>> dirs = {{0,1}, {0,-1},{1,0},{-1,0}};
bool hasPath(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
int n = maze.size(), m = maze[0].size();
visited = vector<vector<bool>>(n, vector<bool>(m, false));
queue<pair<int, int>> q;
q.push({start[0], start[1]});
visited[start[0]][start[1]] = true;
while(!q.empty()){
auto t = q.front();
q.pop();
if(t.first == destination[0] && t.second == destination[1]) return true;
for(const auto &dir : dirs){
int x = t.first, y = t.second;
while(x >= 0 && x < n && y >= 0 && y < m && maze[x][y] == 0){
x += dir[0]; y += dir[1];//一直滚知道碰壁
}
x -= dir[0]; y -= dir[1];
if(!visited[x][y]){
q.push({x, y});
visited[x][y] = true;//标记停下来的点
}
}
}
return false;
}
};
自己在ide上面写一写
bfs,四个方向都考虑就可以了,唯一值得注意的点是每一次碰到墙之后才会停止,所以要使用while循环来求解滚动之后的位置
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int MAXN = 110;
int maze[MAXN][MAXN];
int start[2];
int destination[2];
bool bfs(vector<vector<bool>> &visited, vector<vector<int>> &dirs, int n, int m){
queue<pair<int, int>> q;
q.push({start[0], start[1]});
visited[start[0]][start[1]] = true;
while(!q.empty()){
auto t = q.front();
q.pop();
if(t.first == destination[0] && t.second == destination[1]) return true;
for(const auto &dir : dirs){//遍历每个方向
int x = t.first, y = t.second;
while(x >= 0 && x < n && y >= 0 && y < m && maze[x][y] == 0){
x += dir[0]; y += dir[1];
}
x -= dir[0]; y -= dir[1];//上面加过了
if(!visited[x][y]){
visited[x][y] = true;//标记停下来的点
q.push({x, y});
}
}
}
}
int main(){
int n, m;
cin >> n >> m;
for(int i = 0; i < n; ++i){
for(int j = 0; j < m; ++j)
cin >> maze[i][j];
}
cin >> start[0] >> start[1];
cin >> destination[0] >> destination[1];
vector<vector<bool>> visited(n, vector<bool>(m, false));
vector<vector<int>> dirs = {{0,1}, {0,-1},{1,0},{-1,0}};
bool flag = bfs(visited, dirs, n, m);
if(flag) cout << 1 << endl;
else cout << 0 << endl;
return 0;
}