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
| #coding=utf-8
MIN = 9999999
a = [[0 for col in range(50)] for row in range(50)]#迷宫最大数组
book = [[0 for col in range(50)] for row in range(50)]#标记数组
lujing = ['*']*100
index_step = ['d', 's', 'a', 'w']
def dfs(start_x,start_y,end_x,end_y,migong_array,step):
'''
:param start_x: 起始横坐标
:param start_y: 起始纵坐标
:param end_x: 终点横坐标
:param end_y: 终点纵坐标
:param migong_array: 迷宫的数组
:return:
'''
next_step = [[0,1], #向右走
[1,0], #向下走
[0,-1], #向左走
[-1,0] #向上走
]
if (start_x == end_x and start_y == end_y):
global MIN
if(step < MIN):
MIN = step
return 1
for i in range(len(next_step)):
next_x = start_x + next_step[i][0]
next_y = start_y + next_step[i][1]
if(next_x < 0 or next_y < 0 or next_x > len(migong_array) or next_y > len(migong_array[0])):
continue
if(0<= a[next_x][next_y] <= 1234 and book[next_x][next_y] == 0):
book[next_x][next_y] = 1
if dfs(next_x,next_y,end_x,end_y,migong_array,step+1):
lujing[step] = index_step[i]
return 1
book[next_x][next_y] = 0
return 0
if __name__ == '__main__':
start_x = 0
start_y = 0
end_x = 11
end_y = 11
migong_array = [[545, 3457, 3458, 3459, 3460, 3461, 3462, 3463, 3464, 3465, 3466, 3467], [239, 796, 3470, 3471, 640, 948, 831, 3475, 3476, 3477, 3478, 3479], [3480, 1095, 843, 3483, 766, 3485, 848, 464, 95, 703, 3490, 3491], [3492, 3493, 864, 627, 8, 3497, 3498, 3499, 3500, 1064, 3502, 3503], [3504, 3505, 3506, 3507, 3508, 3509, 881, 600, 985, 706, 3514, 3515], [3516, 3517, 3518, 3519, 3520, 3521, 864, 3523, 3524, 3525, 3526, 3527], [3528, 1214, 779, 709, 804, 3533, 813, 403, 861, 1096, 829, 3539], [3540, 628, 3542, 3543, 494, 3545, 3546, 395, 3548, 3549, 798, 3551], [3552, 988, 3554, 3555, 485, 3557, 3558, 3559, 3560, 674, 777, 3563], [3564, 761, 802, 3567, 412, 568, 829, 721, 217, 1137, 3574, 3575], [3576, 3577, 853, 763, 3580, 3581, 3582, 3583, 3584, 3585, 3586, 3587], [3588, 3589, 3590, 372, 962, 923, 785, 502, 368, 707, 795, 9]] #初始化迷宫
for i in range(len(migong_array)):
for j in range(len(migong_array[0])):
a[i][j] = migong_array[i][j] #将迷宫数组写入a中
book[start_x][start_y] = 1 #将第一步标记为1,证明走过了。避免重复走
dfs(start_x,start_y,end_x,end_y,migong_array,0)
print('The min length of path is : {}'.format(MIN))
print("".join(i for i in lujing)[:MIN])
|