E - 迷宫问题(bfs)

VJ原题链接https://vjudge.net/contest/467285#problem/Ehttps://vjudge.net/contest/467285#problem/E

问题:

 在这会用到 pair<int, int>(pair类型) 来记录当前步数的坐标,然后就是入队出队(队列)

AC代码:

#include<cstdio>
#include<iostream>
#include<queue>
#include<algorithm>
#include<functional>
using namespace std;

typedef pair<int, int> pp;
int a[5][5], vis[5][5];//地图 和 记忆数组

struct node{
	int x, y, step;
	pp p[30];
};
queue<node>q;
int fx[4]= {1, -1, 0, 0}, fy[4] = {0 , 0, 1, -1};//上下左右

void bfs(){
	int i = 0, j;
	node n, temp;
	n.x = 0; n.y = 0; n.step = 0; 
	n.p[n.step++] = pp(n.x, n.y); //记录当前坐标
	q.push(n);
	vis[n.x][n.y] = 1; //走过了哦
	while(!q.empty()){
		temp = q.front();q.pop();
		
		if(temp.x == 4&&temp.y == 4){
			for(i = 0; i < temp.step; i++){
				 cout << '(' << temp.path[i].first << ", " << temp.path[i].second << ')' << endl;
				/*c语言的输出printf("(%d, %d)", (int)temp.p[i].first, (int)temp.p[i].second);
				if(i != temp.step-1) printf("\n");*/
			}
			return ;
		}
		
		for(j = 0; j < 4; j++){
			node next = temp;
			next.x = temp.x + fx[j]; next.y = temp.y + fy[j];
			if(!vis[next.x][next.y] && next.x >= 0 && next.y >= 0 && next.x < 5 && next.x < 5 && a[next.x][next.y] == 0){
				vis[next.x][next.y] = 1;//这个地方没走过(如果走过了自然不是最快的
				next.p[next.step++] = pp(next.x,next.y); //再记录
				q.push(next);
			}	
		}	
	}
}


int main()
{
	int i, j;
	for(i = 0; i < 5; i++){
		for(j = 0; j < 5; j++){
			 cin >> a[i][j]; /*c语言的输入scanf("%d", &a[i][j]);*/
		}
	}
	bfs();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值