bfs记录路径(记录状态的转移)

poj3984

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值