rt。387 的 D 题求调。
#include <bits/stdc++.h>
using namespace std;
const int dx[] = {0, 0, 1, -1};
const int dy[] = {1, -1, 0, 0};
struct Point {
int x, y, dist,derect;
};
bool isValid(int x, int y, int n, int m, const vector<vector<char>>& maze) {
return x >= 1 && x <= n && y >= 1 && y <= m && (maze[x][y] == '.'||maze[x][y]=='G');
}
int bfsMaze(const vector<vector<char>>& maze, const Point& start, const Point& end) {
int n = maze.size();
int m = maze[0].size();
vector<vector<bool>> visited(n, vector<bool>(m, false));
queue<Point> q;
q.push(start);
visited[start.x][start.y] = true;
while (!q.empty()) {
Point current = q.front();
q.pop();
if (current.x == end.x && current.y == end.y) {
return current.dist;
}
for (int i = 0; i < 4; ++i) {
int newX = current.x + dx[i];
int newY = current.y + dy[i];
Point s={newX, newY, current.dist + 1,i};
if (isValid(newX, newY, n, m, maze) && !visited[newX][newY] && current.derect!=s.derect) {
visited[newX][newY] = true;
q.push({newX, newY, current.dist + 1,i});
}
}
}
return -1;
}
vector<vector<char>>maze(1005,vector<char>(1005));
int main() {
int H,W;
cin>>H>>W;
Point start = {0,0,0,-1};
Point end = {H,W,0,-1};
for(int i=1;i<=H;i++){
for(int j=1;j<=W;j++){
cin>>maze[i][j];
if(maze[i][j]=='S')start={i,j,0,-1};
else if(maze[i][j]=='G')end={i,j,0,-1};
}
}
int result = bfsMaze(maze, start, end);
if (result != -1) {
cout << result << endl;
} else {
cout << "-1" << endl;
}
return 0;
}
代码由 AI 生成的 BFS 模板改的。