7-5 最近距离 (25 分) 迷宫问题

在这里插入图片描述

#include<iostream>
#include<queue>
using namespace std;
int a[][12] = {
	0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1,

	0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1,

	0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0,

	0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1,

	0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,

	0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0,

	0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0,

	1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1,

	0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0,

	0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0,

	0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,

	0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0,
};
int vis[15][15];
int dx[4] = {0, 1, 0, -1};//按顺时针方向进行扩展
int dy[4] = { 1, 0, -1, 0};
struct pp {
	int x, y;//坐标
	int num;//步数
} p;//用队列储存,所以使用一个结构体
queue<pp> q;
int x, y, c, d, flag = 1; //标志看能否到达规定的点;
void bfs() {
	while (!q.empty()) { //通过队列的特性,逐渐加大探索范围
		int x1 = q.front().x, y1 = q.front().y; //取出头的点,从四个方向进行扩展
		if (x1 == c && y1 == d) {
			flag = 0;
			cout << q.front().num << endl;
			return; //到达目的地,跳出队列循环
		}
		for (int i = 0; i < 4; i++) {
			int xx = x1 + dx[i];
			int yy = y1 + dy[i]; //从四个方向进行探索
			if (xx < 0 || yy < 0 || xx > 12 || yy > 12 || a[xx][yy] || vis[xx][yy]) continue;
			//数越界的判断,以及障碍物,标记点的判断
			else {//若能通过该图的障碍物,且未被访问过,则可以入队
				pp t;
				t.num = q.front().num + 1; //更新步数
				t.x = xx;
				t.y = yy;
				q.push(t);
				vis[xx][yy] = 1;//注意被探索到的点要标记
			}
		}
		q.pop();//该点探索完毕,释放
	}
}
int main() {
	cin >> x >> y >> c >> d;
	p.x = x;
	p.y = y;
	p.num = 0;
	q.push(p);
	vis[x][y] = 1;
	bfs();
	if (flag) cout << 10000;
	return 0;
}

dfs方式:

#include <stdio.h>
int map[12][12] = { 0,1,0,0,0,1,1,1,0,1,0,1,

					0,0,0,1,0,0,0,0,1,0,0,1,
					
					0,1,0,1,0,1,1,1,0,1,0,0,
					
					0,1,0,0,0,0,0,1,0,0,1,1,
					
					0,0,0,0,1,0,0,0,0,0,0,0,
					
					0,0,1,0,0,0,1,0,0,0,1,0,
					
					0,0,1,0,0,0,0,0,1,0,0,0,
					
					1,0,0,1,0,1,0,0,0,1,0,1,
					
					0,0,1,0,1,0,1,0,1,0,0,0,
					
					0,0,0,0,0,1,0,0,0,1,1,0,
					
					0,0,0,0,0,1,0,0,0,0,0,0,
					
					0,1,0,1,0,0,0,1,0,1,0,0};//初始地图 
int c, d, count, min = 10000;
int A[4] = {-1, 1, 0, 0};//a的方向 
int B[4] = {0, 0, -1, 1};//b的方向 
void dfs(int a, int b)
{
	if (a == c && b == d)//走到终点就输出 
	{
		if (count < min)
		{
			min = count;
		}
	}
	else
	{
		for (int i = 0; i < 4; i++)
		{
	if (a + A[i] >= 0 && a + A[i] < 12 && b + B[i] >= 0 && b + B[i] < 12
			&& !map[a + A[i]][b + B[i]] && count < min)//剪枝 
			{
				map[a + A[i]][b + B[i]] = 1;
				count++;
				dfs(a + A[i], b + B[i]);
				count--;
				map[a + A[i]][b + B[i]] = 0;
			}
		}
	}
}
int main()
{
	int a, b;
	scanf("%d%d%d%d", &a, &b, &c, &d);
	dfs(a, b);
	printf("%d", min);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值