北邮 信通院 数据结构 实验二-4 迷宫求解问题

北邮 信通院 数据结构 实验二-4 迷宫求解问题
从迷宫中的任意位置进入,能否到达任意位置
仅供学习交流使用

#include <iostream>
using namespace std;

//可用const int hang=6,lie=8;进行数组行列大小宏定义,即int map1[hang+2][lie+2];
int map1[8][10] = { {1,1,1,1,1,1,1,1,1,1},{1,0,1,1,1,0,1,1,1,1},{1,1,0,1,0,1,1,1,1,1},
{1,0,1,0,0,0,0,0,1,1},{1,0,1,1,1,0,1,1,1,1},{1,1,0,0,1,1,0,0,0,1},{1,0,1,1,0,0,1,1,0,1},
{1,1,1,1,1,1,1,1,1,1} };
int map2[8][10] = { {1,1,1,1,1,1,1,1,1,1},{1,0,1,1,1,0,1,1,1,1},{1,1,0,1,0,1,1,1,1,1},
{1,0,1,0,0,0,0,0,1,1},{1,0,1,1,1,0,1,1,1,1},{1,1,0,0,1,1,0,0,0,1},{1,0,1,1,0,0,1,1,0,1},
{1,1,1,1,1,1,1,1,1,1} };
int m, n, o, p;
int mark[8][10] = { {0},{0},{0},{0} ,{0} ,{0} ,{0} ,{0} };
class direction
{
public:
	int a, b;
	direction(int x, int y)
	{
		a = x; b = y;
	}
};
direction d[8] = { {1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1},{0,1},{1,1} };
//第一种从东方向开始顺时针转动
//direction d[8] = { {1,-1},{1,0},{1,1} ,{0,1},{-1,1},{-1,-1} ,{-1,0},{0,-1} };
//第二种从东南方向开始逆时针转动
//direction d[7] = { {1,0},{1,-1},{0,-1},{-1,0},{-1,1},{0,1},{1,1} };
//第三种从东方向开始顺时针转动(去掉西南方向)
//direction d[7] = { {1,-1},{1,0},{1,1} ,{0,1},{-1,-1} ,{-1,0},{0,-1} };
//第四种从东南方向开始逆时针转动(去掉西北方向)
//direction d[7] = { {1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1},{0,1} };
//第五种从东方向开始顺时针转动(去掉东北方向)
//direction d[7] = { {1,-1},{1,0} ,{0,1},{-1,1},{-1,-1} ,{-1,0},{0,-1} };
//第六种从东南方向开始逆时针转动(去掉东北方向)
//direction d[7] = { {1,0},{1,-1},{0,-1},{-1,0},{-1,-1},{0,1},{1,1} };
//第七种从东方向开始顺时针转动(去掉西北方向)
bool path(int x, int y)
{
	int g, h;
	if (x == m && y == n)
		return true;
	else
	{
		for (int i = 0; i < 8; i++)
			//第一种、第二种为 i<8;第三种、第四种、第五种、第六种、第七种为i<7;
		{
			g = x + d[i].a;
			h = y + d[i].b;
			if (mark[g][h] == 0 && map1[g][h] == 0)
			{
				mark[g][h] = 1;
				if (path(g, h)) {
					cout << "(" << g << "," << h << ")" << ",";
					map2[g][h] = 6;
					return true;
				}
			}
		}
		return false;
	}
}

int main()
{
	cout << "该迷宫如下所示:" << endl;
	for (int i = 0; i < 8; i++)
	{
		for (int j = 0; j < 10; j++)
			cout << map1[i][j] << " ";
		cout << endl;
	}
	cout << "请输入起点坐标:";
	cin >> o >> p;
	cout << "请输入终点坐标:";
	cin >> m >> n;
	mark[o][p] = 1;
	map2[o][p] = 6;
	cout << "走出迷宫的路径为:" << endl;
	if (path(o, p))
	{
		cout << "(" << o << ", " << p << ")" << endl;
		for (int i = 0; i < 8; i++)
		{
			for (int j = 0; j < 10; j++)
				cout << map2[i][j] << " ";
			cout << endl;
		}
	}
	else cout << "未找到走出迷宫的路径";
}

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值