BFS求解迷宫

bfs 广度优先遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include <cstdio>
#include <iostream>
#include <queue>
#include <stack>
using namespace std;

const int MaxN = 105;
int n, m;
int maze[MaxN][MaxN];
bool vis[MaxN][MaxN];
int fa[MaxN][MaxN], dist[MaxN][MaxN], last_dir[MaxN][MaxN];

///u, d, l, r
int dx[4] = {0, 0, -1, 1};
int dy[4] = {1, -1, 0, 0};
char name[4] = {'r', 'l', 'u', 'd'};

bool inbound(int x, int l, int r)
{
if (x >= l)
if (x < r)
return true;
else
return false;
else
return false;
}

void bfs(int x, int y)
{
int d = 0;
int u = x * m + y;
vis[x][y] = 1;
fa[x][y] = u;
dist[x][y] = 0;
queue<int> q;
q.push(u);
while (!q.empty())
{
u = q.front(); q.pop();
x = u / m; y = u % m;
for (d = 0; d < 4; d++)
{
int nx = x + dx[d];
int ny = y + dy[d];
if (inbound(nx, 0, n) && inbound(ny, 0, m)
&& maze[nx][ny] && !vis[nx][ny])
{
int v = nx * m + ny;
q.push(v);
vis[nx][ny] = 1;
fa[nx][ny] = u;
//cout<<"fa:"<<" nx:"<<nx<<" ny:"<<ny<<" u:"<<u<<endl;
dist[nx][ny] = dist[x][y] + 1;
last_dir[nx][ny] = d;
// cout<<"dir: "<<d<<endl;
}
}
}

return;
}

void init()
{
freopen("maze.in", "r", stdin);
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
scanf("%d", &maze[i][j]);
puts("打印迷宫:");
printf("i \\ j ");
for (int j = 0; j < m; j++)
printf("%7d:", j);
printf("\n");
for (int i = 0; i < n; i++)
{
printf("%4d: ", i);
for (int j = 0; j < m - 1; j++)
printf("%8d", maze[i][j]);
printf("%8d\n", maze[i][m - 1]);
}
puts("输入终点坐标");
bfs(0, 0);
}

void print(int x, int y)
{
stack<int> dir;
cout<<endl;
while (true)
{
int fx = fa[x][y] / m;
int fy = fa[x][y] % m;
// cout<<" fx:"<fx<<" fy:"<<fy<<endl;
//cout<<" x:"<<x<<" y:"<<y<<endl;
if (fx == x && fy == y) break;
dir.push(last_dir[x][y]);
x = fx; y = fy;
}
while (!dir.empty())
{
printf("%c", name[dir.top()]);
dir.pop();
}
}

int main()
{
init();
freopen("CON", "r", stdin);
int sx, sy;
scanf("%d%d", &sx, &sy);
// sx=3;
// sy=3;
print(sx, sy);
return 0;
}

image
参考链接
https://blog.csdn.net/s_lisheng/article/details/73799880