1 def init():
2 global graph
3 graph.append([-1, -1, -1, -1, -1, -1, -1])
4
5 graph.append([-1, 0, 0, -1, 0, 0, -1])
6 graph.append([-1, 0, -1, 0, 0, 0, -1])
7 graph.append([-1, 0, -1, 0, -1, -1, -1])
8 graph.append([-1, 0, -1, 0, 0, 0, -1])
9 graph.append([-1, 0, 0, 0, -1, 0, -1])
10 graph.append([-1, 0, 0, 0, 0, 0, -1])
11
12 graph.append([-1, -1, -1, -1, -1, -1, -1])
13
14 #深度优先遍历
15 def deepFirstSearch( steps , x, y ):
16
17 global graph
18 current_step = steps + 1
19 print(x, y, current_step )
20
21 graph[x][y] = current_step
22 next_step = current_step + 1
23 '''
24 遍历周围4个点:
25 如果周围节点不是-1 说明 不是障碍 在此基础上:
26 里面是0 说明没遍历过 我们把它修改成当前所在位置步数加1
27 里面比当前的next_step大 说明不是最优方案 就修改它
28 里面比当前next_step说明当前不是最优方案,不修改
29 '''
30
31 if not(x-1== 1 and y==1) and graph[x-1][y] != -1 and ( graph[x-1][y]>next_step or graph[x-1][y] ==0 ) : #左
32 deepFirstSearch(current_step, x-1 , y )
33 if not(x == 1 and y-1==1) and graph[x][y-1] != -1 and ( graph[x][y-1]>next_step or graph[x][y-1] ==0 ) : #上
34 deepFirstSearch(current_step, x , y-1 )
35 if not(x == 1 and y+1==1) and graph[x][y+1] != -1 and ( graph[x][y+1]>next_step or graph[x][y+1]==0 ) : #下
36 deepFirstSearch(current_step, x , y+1 )
37 if not(x+1== 1 and y==1) and graph[x+1][y] != -1 and ( graph[x+1][y]>next_step or graph[x+1][y]==0 ) : #右
38 deepFirstSearch(current_step, x+1 , y )
39
40
41
42
43 if __name__ == "__main__":
44 graph = []
45 init()
46
47 deepFirstSearch(-1,1,1)
48 print(graph[1][5])