XDU 1196

本文介绍了一种解决迷宫问题的算法实现,通过使用广度优先搜索(BFS)来寻找从起点到终点的最短路径。文章提供了完整的C++代码示例,并详细解释了如何读取迷宫地图数据及进行路径探索的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单迷宫题,貌似哪里写过,So,一遍AC

考点貌似在判断上,或者说,没有。。

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;

int vis[31][31];
int walls[60][31];
int w, h;
int dir[4][2] = {
	1, 0, -1, 0, 0, 1, 0, -1
};

int main()
{
	cin >> w >> h;
	while(w){
		memset(vis, 0, sizeof(vis));
		memset(walls, 0, sizeof(walls));
		
		for(int i = 1; i <= 2*h-1; i++)
			if(i%2){
				for(int j = 1; j <= w - 1; j++)
					cin >> walls[i][j];
			}else
				for(int j = 1; j <= w; j++)
					cin >> walls[i][j];
					
		vis[1][1] = 1;
		queue<short> qw;
		queue<short> qh;
		qw.push(1); qh.push(1);
		while(!qw.empty()){
			short x = qh.front(), y = qw.front(), step = vis[x][y];
			qw.pop(); qh.pop();
			
			if(x == h && y == w)
				break;
			
			for(int i = 0; i < 4; i++){
				short newx = x + dir[i][0], newy = y + dir[i][1];
 				if(newx >= 1 && newx <= h && newy >= 1 && newy <= w){
 					short tempx = x < newx ? x : newx;
					short wallx = x == newx ? 2*(tempx-1)+1 : 2*tempx;
					short wally = y < newy ? y : newy;
					int newstep = step+1;
					if(!walls[wallx][wally]){
						if(!vis[newx][newy]){
							vis[newx][newy] = newstep;
							qw.push(newy);
							qh.push(newx);
						}else if(newstep < vis[newx][newx]){
							vis[newx][newy] = newstep;
						}
					}
				}
			}
		}
		
		if(vis[h][w])
			cout << vis[h][w] << endl;
		else
			cout << "0" << endl;
		
		cin >> w >> h;
	}
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值