#include<iostream>
#include<string>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<algorithm>
#define ll long long
#define inf 0x3f3f3f3f
#define endl '\n'
#define IOS std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0)
using namespace std;
const int N = 1e5 + 10;
int n, m, cnt;
char a[505][505];
bool vis[505][505];
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
struct node
{
int x, y;
int t;
}fa[505][505], jg[100];
void bfs()
{
queue<node> Q;
node head;
head.x = 0, head.y = 0, head.t = 1;
Q.push(head);
while(Q.size() >= 1)
{
node now = Q.front();
Q.pop();
for(int i = 0; i < 4; i ++)
{
int xx = now.x + dx[i], yy = now.y + dy[i];
if(xx < 0 || yy < 0 || xx >= 5 || yy >= 5) continue;
if(xx == 5 - 1 && yy == 5 - 1)
{
jg[cnt].x = xx, jg[cnt].y = yy;
cnt ++;
node L = now;
while(L.x != 0 || L.y != 0) //同为0才停止
{
jg[cnt].x = L.x, jg[cnt].y = L.y;
cnt ++;
L = fa[L.x][L.y]; //往回找父亲,直到找到起点
}
jg[cnt].x = 0, jg[cnt].y = 0;
cnt ++;
for(int o = cnt - 1; o >= 0; o --)
cout << "(" << jg[o].x << ", " << jg[o].y << ")" << endl;
return;
}
if(vis[xx][yy]) continue;
if(a[xx][yy] != '1')
{
vis[xx][yy] = 1;
node next;
next.x = xx, next.y = yy, next.t = now.t + 1;
fa[xx][yy] = now; //是用来记录父亲节点的,now是父亲
Q.push(next);
}
}
}
return ;
}
int main()
{
for(int i = 0; i < 5; i ++)
for(int j = 0; j < 5; j ++)
cin >> a[i][j];
bfs();
return 0;
}
bfs记录路径(记录状态的转移)
最新推荐文章于 2023-12-05 14:32:35 发布