记录迷宫问题解法JavaScript实现
问题描述
给定一个迷宫,指明起点和终点,找出从起点出发到终点的有效可行路径,就是迷宫问题(maze problem)
迷宫可以以二维数组来存储表示。0表示通路,1表示障碍。注意这里规定移动可以从上、下、左、右四方方向移动。坐标以行和列表示,均从0开始,给定起点(0,0)和终点(4,4),迷宫表示如下
1 | const maze = [ |
广度优先搜索解法
1 | const MAX_ROW = 5 |
输出结果如下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[ 6, 1, 0, 0, 0 ]
[ 6, 1, 0, 1, 0 ]
[ 0, 0, 0, 0, 0 ]
[ 0, 1, 1, 1, 0 ]
[ 0, 0, 0, 1, 0 ]
/************************/
[ 6, 1, 0, 0, 0 ]
[ 6, 1, 0, 1, 0 ]
[ 6, 0, 0, 0, 0 ]
[ 0, 1, 1, 1, 0 ]
[ 0, 0, 0, 1, 0 ]
/************************/
[ 6, 1, 0, 0, 0 ]
[ 6, 1, 0, 1, 0 ]
[ 6, 6, 0, 0, 0 ]
[ 6, 1, 1, 1, 0 ]
[ 0, 0, 0, 1, 0 ]
/************************/
[ 6, 1, 0, 0, 0 ]
[ 6, 1, 0, 1, 0 ]
[ 6, 6, 0, 0, 0 ]
[ 6, 1, 1, 1, 0 ]
[ 6, 0, 0, 1, 0 ]
/************************/
[ 6, 1, 0, 0, 0 ]
[ 6, 1, 0, 1, 0 ]
[ 6, 6, 6, 0, 0 ]
[ 6, 1, 1, 1, 0 ]
[ 6, 0, 0, 1, 0 ]
/************************/
[ 6, 1, 0, 0, 0 ]
[ 6, 1, 0, 1, 0 ]
[ 6, 6, 6, 0, 0 ]
[ 6, 1, 1, 1, 0 ]
[ 6, 6, 0, 1, 0 ]
/************************/
[ 6, 1, 0, 0, 0 ]
[ 6, 1, 6, 1, 0 ]
[ 6, 6, 6, 6, 0 ]
[ 6, 1, 1, 1, 0 ]
[ 6, 6, 0, 1, 0 ]
/************************/
[ 6, 1, 0, 0, 0 ]
[ 6, 1, 6, 1, 0 ]
[ 6, 6, 6, 6, 0 ]
[ 6, 1, 1, 1, 0 ]
[ 6, 6, 6, 1, 0 ]
/************************/
[ 6, 1, 0, 0, 0 ]
[ 6, 1, 6, 1, 0 ]
[ 6, 6, 6, 6, 6 ]
[ 6, 1, 1, 1, 0 ]
[ 6, 6, 6, 1, 0 ]
/************************/
[ 6, 1, 6, 0, 0 ]
[ 6, 1, 6, 1, 0 ]
[ 6, 6, 6, 6, 6 ]
[ 6, 1, 1, 1, 0 ]
[ 6, 6, 6, 1, 0 ]
/************************/
[ 6, 1, 6, 0, 0 ]
[ 6, 1, 6, 1, 0 ]
[ 6, 6, 6, 6, 6 ]
[ 6, 1, 1, 1, 0 ]
[ 6, 6, 6, 1, 0 ]
/************************/
[ 6, 1, 6, 0, 0 ]
[ 6, 1, 6, 1, 6 ]
[ 6, 6, 6, 6, 6 ]
[ 6, 1, 1, 1, 6 ]
[ 6, 6, 6, 1, 0 ]
/************************/
[ 6, 1, 6, 6, 0 ]
[ 6, 1, 6, 1, 6 ]
[ 6, 6, 6, 6, 6 ]
[ 6, 1, 1, 1, 6 ]
[ 6, 6, 6, 1, 0 ]
/************************/
[ 6, 1, 6, 6, 0 ]
[ 6, 1, 6, 1, 6 ]
[ 6, 6, 6, 6, 6 ]
[ 6, 1, 1, 1, 6 ]
[ 6, 6, 6, 1, 6 ]
/************************/
[ 6, 1, 6, 6, 6 ]
[ 6, 1, 6, 1, 6 ]
[ 6, 6, 6, 6, 6 ]
[ 6, 1, 1, 1, 6 ]
[ 6, 6, 6, 1, 6 ]
/************************/
[ 6, 1, 6, 6, 6 ]
[ 6, 1, 6, 1, 6 ]
[ 6, 6, 6, 6, 6 ]
[ 6, 1, 1, 1, 6 ]
[ 6, 6, 6, 1, 6 ]
/************************/
4 4
3 4
2 4
2 3
2 2
2 1
2 0
1 0
0 0