离开中山路(深搜or宽搜)

本文介绍了一个简单的迷宫问题解决方案,通过宽度优先搜索(BFS)算法找到从起点到终点的最短路径。使用C++实现,并详细展示了如何遍历地图、标记已访问节点及记录路径长度。

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


原题连接:离开中山路

非常的简单,我是用宽搜写的

#include<bits/stdc++.h>
#define N 1005
using namespace std;
int n;
char a[N][N];
int dx[] = {-1, 0, 0, 1};
int dy[] = {0, -1, 1, 0};
int vis[N][N];
bool f[N][N];
queue <pair <int, int> > Q;
int main() {
	cin >> n;
	for (int i = 0; i < n; i++) {
		string asdf;
		cin >> asdf;
		for (int j = 0; j < n; j++)
			a[i + 1][j + 1] = asdf[j];		
	}
	int x, y, x1, y1;
	cin >> x >> y >> x1 >> y1;
	f[x][y] = true;
	Q.push (make_pair (x, y));
	while (Q.size ()) {
		int xx = Q.front ().first;
		int yy = Q.front ().second;
		Q.pop ();
		for (int i = 0; i < 4; i++) {
			int tx = xx + dx[i];
			int ty = yy + dy[i];
			if (f[tx][ty] || tx < 1 || ty < 1 || tx > n || ty > n || a[tx][ty] == '1') continue;
			f[tx][ty] = true;
			vis[tx][ty] = vis[xx][yy] + 1;
			Q.push (make_pair (tx, ty));
		}
	}
	cout << vis[x1][y1] << endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值