赛时交了三发,写了两发 DFS 一发 BFS,赛后调了一会没调出来
BFS 直接改造 DFS 而成,AC 38 WA 19
#include <bits/stdc++.h>
#define endl '\n'
typedef long long ll;
using namespace std;
const int N = 1e3 + 10;
char graph[N][N];
bool vis[N][N];
int sblockx = 0, sblocky = 0;
int ANS = 0x7fffffff;
int n, m;
queue<pair<pair<int, int>, pair<bool, int>>> q;
void bfs()
{
q.push({{sblockx, sblocky}, {0, 0}});
q.push({{sblockx, sblocky}, {1, 0}});
while (!q.empty())
{
int i = q.front().first.first;
int j = q.front().first.second;
bool isodd = q.front().second.first;
int ans = q.front().second.second;
q.pop();
if (graph[i][j] == 'G')
{
ANS = min(ANS, ans);
continue;
}
if (isodd)
{
isodd = !isodd;
if (!vis[i][j + 1] && 1 <= j + 1 && j + 1 <= m)
{
vis[i][j + 1] = true;
q.push({{i, j + 1}, {isodd, ans + 1}});
}
if (!vis[i][j - 1] && 1 <= j - 1 && j - 1 <= m)
{
vis[i][j - 1] = true;
q.push({{i, j - 1}, {isodd, ans + 1}});
}
}
else
{
isodd = !isodd;
if (!vis[i + 1][j] && 1 <= i + 1 && i + 1 <= n)
{
vis[i + 1][j] = true;
q.push({{i + 1, j}, {isodd, ans + 1}});
}
if (!vis[i - 1][j] && 1 <= i - 1 && i - 1 <= n)
{
vis[i - 1][j] = true;
q.push({{i - 1, j}, {isodd, ans + 1}});
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
cin >> graph[i][j];
if (graph[i][j] == '#')
{
vis[i][j] = true;
}
if (graph[i][j] == 'S')
{
sblockx = i;
sblocky = j;
}
}
}
bfs();
cout << (ANS == 0x7fffffff ? -1 : ANS) << endl;
return 0;
}