Skip to content

Commit 463fe7e

Browse files
authored
Create maze.cpp
1 parent a8ae281 commit 463fe7e

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

backtracking/maze.cpp

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
迷宫问题
3+
author:fangrm
4+
*/
5+
6+
#include <iostream>
7+
#include <stack>
8+
using namespace std;
9+
10+
int top = -1; //-1表示还没开始走
11+
12+
//迷宫数组,0:可行 1:不可行
13+
int maze[5][5]={
14+
{0, 0, 0, 0, 0},
15+
{0, 1, 0, 1, 0},
16+
{0, 1, 1, 0, 0},
17+
{0, 1, 1, 0, 1},
18+
{0, 0, 0, 0, 0}
19+
};
20+
21+
//储存迷宫位置的结构体
22+
struct place
23+
{
24+
int col; //位置的列坐标
25+
int row; //位置的行坐标
26+
}p[100];
27+
28+
//回溯法求路径 (xi, yi)表示当前位置 (xe, ye)表示目标位置
29+
void backtracking (int xi, int yi, int xe, int ye)
30+
{
31+
if (xe == xi && ye == yi) //若到达目的地则输出路径
32+
{
33+
cout << "迷宫路径如下:" << endl;
34+
for (int i = 0; i <= top; i++)
35+
cout << "(" << p[i].col << ", " << p[i].row << ") -> ";
36+
cout << endl;
37+
return;
38+
}
39+
else
40+
{
41+
int x, y;
42+
top += 1;
43+
p[top].col = xi;
44+
p[top].row = yi;
45+
for (int i = 0; i < 4; i++) //搜索这位置的可行路径
46+
{
47+
switch (i)
48+
{
49+
case 0 : x = xi + 1; y = yi; break;
50+
case 1 : x = xi; y = yi + 1; break;
51+
case 2 : x = xi - 1; y = yi; break;
52+
case 3 : x = xi; y = yi - 1; break;
53+
}
54+
if (x >= 0 && y >= 0 && maze [y][x] == 0) //若为通路
55+
{
56+
backtracking (x, y, xe, ye);
57+
top -= 1;
58+
}
59+
}
60+
}
61+
}
62+
63+
int main ()
64+
{
65+
cout << "请输入目的地:";
66+
int xe, ye;
67+
cin >> xe >> ye;
68+
backtracking (0, 0, 4, 4);
69+
}

0 commit comments

Comments
 (0)