【K - 迷宫问题】

思路:

  • BFS,记录路径。
  • 简化版的【H - Pots】
  • 总结:
    1. 队列存状态,反序输出,结构体类型。
    2. 结构体中的前驱数组编号。
    3. 边界停止搜索,标记不要忘记。

代码:

  • 0ms 676kB
//0ms	676kB


#include <iostream>
#include <queue>
#include <stack>

using namespace std;

const int mt[4][2] = {1,0 , -1,0 , 0,1 , 0,-1};//moveto

bool vis[5][5];
struct grid{
	int x,y;
	int pre;
};
grid G[105];int cnt = 1;//5*5*4
queue<grid> Q;
stack<grid> S;

void PUSHGRID(int x,int y,int pre){
	grid t;
	t.x = x;
	t.y = y;
	t.pre = pre;
	Q.push(t);
	vis[x][y] = true;//highlight
	return ;
}

void BFS(){
	while(Q.size()){
		grid cur = Q.front();Q.pop();
		G[cnt++] = cur;
		int x = cur.x;
		int y = cur.y;
		if(x == y && x == 4)
			return ;
		for(int i=0;i<4;i++){
			int nx = x + mt[i][0];
			int ny = y + mt[i][1];
			if(nx < 0 || ny < 0 || nx > 4 || ny > 4)
				continue;//highlight
			if(vis[nx][ny])
				continue;
			PUSHGRID(nx , ny , cnt-1);
		}
	}
	return ;
}

void OUTPUT(){
	grid cur = G[cnt-1];
	while(true){
		S.push(cur);
		if(!cur.pre)
			break;
		cur = G[cur.pre];
	}
	while(S.size()){
		cur = S.top();S.pop();
		cout<<'('<<cur.x<<','<<' '<<cur.y<<')'<<endl;
	}
	return ;
}

int main(){
	for(int i=0;i<5;i++)
		for(int j=0;j<5;j++)
			cin>>vis[i][j];
	PUSHGRID(0,0,0);
	BFS();
	OUTPUT();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值