活动 - AcWing(迷宫)
思路:构建pre数组,bfs同时求前一个状态
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define PII pair<int, int>
#define PLL pair<ll, ll>
const int N = 1010;
const int M = 2 * N;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const double PI = acos(-1.0);
const double eps = 1e-8;
int n;
int g[N][N];
PII pre[N][N];
int hr[4][2] = {{0,-1},{-1,0},{0,1},{1,0}};
void bfs(int x,int y)
{
queue<PII>q;
q.push({x,y});
memset(pre, -1, sizeof pre);
while(q.size())
{
PII t = q.front();
q.pop();
for(int i = 0; i < 4; i ++)
{
int a = t.first + hr[i][0];
int b = t.second + hr[i][1];
if(a < 0 || a >= n || b < 0 || b >= n) continue;
if(g[a][b]) continue;
if(pre[a][b].first != -1) continue;
q.push({a,b});
pre[a][b] = t;
}
}
}
void solve()
{
cin >> n;
for(int i = 0; i < n; i ++)
for(int j = 0; j < n; j ++)
cin >> g[i][j];
bfs(n - 1,n - 1);
PII end(0,0);
while(true)
{
printf("%d %d\n",end.first,end.second);
if(end.first == n - 1 && end.second == n - 1) break;
else end = pre[end.first][end.second];
}
}
int main()
{
solve();
system("pause");
return 0;
}
思路:bfs搜索是层序搜索,保证了dij方式的拓扑有序,可以通过标记重复减少一些冗余操作。同时可以开dist取min
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define PII pair<int, int>
#define PLL pair<ll, ll>
const int N = 160;
const int M = 2 * N;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const double PI = acos(-1.0);
const double eps = 1e-8;
char mp[N][N];
int sx,sy,ex,ey;
int c,r;
int dist[N][N];
bool st[N][N];
int hr[8][2] = {{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}};
void bfs(int sx,int sy)
{
memset(dist,INF,sizeof dist);
queue<PII>q;
q.push({sx,sy});
dist[sx][sy] = 0;
while(q.size())
{
auto t = q.front();
q.pop();
if(t.first == ex && t.second == ey) break;
for(int i = 0; i < 8; i ++)
{
int a = t.first + hr[i][0];
int b = t.second + hr[i][1];
if(a < 0 || a >= r || b < 0 || b >= c) continue;
if(st[a][b]) continue;
if(mp[a][b] == '*') continue;
if(dist[a][b] > dist[t.first][t.second] + 1)
{
dist[a][b] = dist[t.first][t.second] + 1;
q.push({a,b});
}
}
}
}
void solve()
{
cin >> c >> r;
for(int i = 0; i < r; i ++) cin >> mp[i];
for(int i = 0; i < r; i ++)
for(int j = 0; j < c; j ++)
{
if(mp[i][j] == 'K')
{
sx = i;
sy = j;
}
if(mp[i][j] == 'H')
{
ex = i;
ey = j;
}
}
bfs(sx,sy);
cout << dist[ex][ey] << endl;
}
int main()
{
solve();
system("pause");
return 0;
}