[Coursera]算法基础_Week7_广搜_Q2

本文介绍了一种基于递归深度优先搜索的迷宫寻路算法,并提供了完整的C++实现代码。该算法通过记录路径来寻找从起点到终点的通路。

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

#include <iostream>
#include <stack>
#include <string.h>
using namespace std;
struct Point {
	int x;
	int y;
	Point(int x_,int y_):x(x_),y(y_){}
};
int map[7][7];
int pace[7][7];
int rout[7][7];
int f(int p) {
	for (int x = 1; x <= 5; x++) {
		for (int y = 1; y <= 5; y++) {
			if (pace[x][y] == p) {
				if (x == 5 && y == 5)
					return 1;
				if (map[x][y + 1] == 0 && pace[x][y + 1] == -1)
					pace[x][y + 1] = p + 1;
				if (map[x][y - 1] == 0 && pace[x][y - 1] == -1)
					pace[x][y - 1] = p + 1;
				if (map[x+1][y] == 0 && pace[x+1][y] == -1)
					pace[x+1][y] = p + 1;
				if (map[x-1][y] == 0 && pace[x-1][y] == -1)
					pace[x-1][y] = p + 1;
			}
		}
	}
	return 0;
}
Point find(int x, int y, int p) {
	if (pace[x][y + 1] == p - 1)
		return Point(x, y + 1);
	if (pace[x][y - 1] == p - 1)
		return Point(x, y - 1);
	if (pace[x - 1][y] == p - 1)
		return Point(x - 1, y);
	if (pace[x + 1][y] == p - 1)
		return Point(x + 1, y);
}
int main() {
	for (int x = 1; x <= 5; x++) {
		for (int y = 1; y <= 5; y++)
			cin >> map[x][y];
	}
	for (int i = 0; i <= 5 + 1; i++) {
		map[i][0] = 1, map[i][5 + 1] = 1;
	}
	for (int j = 0; j <= 5 + 1; j++) {
		map[0][j] = 1, map[5 + 1][j] = 1;
	}
	memset(pace, -1, sizeof(pace));
	pace[1][1] = 0;
	int p = 0;
	while (true) {
		int t = f(p);
		if (t == 1)
			break;
		p++;
	}
	stack<Point> s;
	s.push(Point(5, 5));
	while (p > 0) {
		Point temp = find(s.top().x, s.top().y, p);
		s.push(temp);
		p--;
	}
	while (s.size() != 0) {
		cout << '(' << s.top().x - 1 << ", " << s.top().y - 1 << ')';
		s.pop();
		if (s.size() != 0)
			cout << endl;
	}
		
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值