算法:深度优先搜索之迷宫寻径

Posted 我的时光穿梭机

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法:深度优先搜索之迷宫寻径相关的知识,希望对你有一定的参考价值。

深度优先搜索(depth-first search, DFS):一种试图穷尽所有可能直到抵达问题边界条件,然后依次返回搜索结果的算法。本质是递归实现。


以下是在迷宫中走最短路径的算法实现。结果会返回所有可能路径以及一条最短路径。

# To define a stack.
class Stack():
def __init__(self,stack):
self.stack = stack
self.head = 0
self.tail = len(self.stack)
def push(self,element):
self.stack.append('')
self.stack[self.tail] = element
self.tail += 1
def pop(self):
self.tail -= 1
pop_item = self.stack[self.tail]
self.stack = self.stack[self.head:self.tail]
return pop_item
def peek(self):
return self.stack[self.tail-1]
def is_empty(self):
return self.head >= self.tail
def size(self):
return len(self.stack[self.head:self.tail])
def clear(self):
self.stack.clear()
self.head = self.tail
# To define a maze.
maze = [
'..#.',
'....',
'..#.',
'.#T.',
'...#',
]
# A depth first search function to probe the maze until a walkable path is found.
def walk(x,y):
# plan: store the number of walkable paths.
global plan
# inc: store the increment (or direction) per step.
inc = [(0,1),(1,0),(-1,0),(0,-1)]
# flag: store the availability status ('0': available, has not been probed; '1': unavailable, has already been probed;) of current (x,y) or next (nx,ny) step.
flag.setdefault((x,y),1)
for i in range(4):
# (nx,ny): coordinate of next step.
nx = x+inc[i][0]
ny = y+inc[i][1]
flag.setdefault((nx,ny),0)
# To identify the walkable status of next step. If the next step has been out of the maze borders or blocked by a barrier ('#') or probed (flag == 1), then it is skipped.
if nx < 0 or nx > row-1 or ny <0 or ny > clmn-1 or maze[nx][ny] == '#' or flag[(nx,ny)] == 1:
continue
else:
# If next step is our target, this round of probing shall be ended and recorded.
if maze[nx][ny] == 'T':
stc.push((nx,ny))
path.setdefault(plan,stc.stack)
stc.pop()
plan += 1
return
# If next step is walkable, the probing shall be repeated by taking the next step as current step.
# Before probing, the next step should be marked as 'walked' (flag == 1) and pushed into the stack. After probing, the next step should be marked as 'walkable' (flag == 0) and popped out of the stack. This is critical for proper running of the recursion.
if maze[nx][ny] == '.':
flag[(nx,ny)] = 1
stc.push((nx,ny))
walk(nx,ny)
stc.pop()
flag[(nx,ny)] = 0
# return all the possible strategies to walk to the target.
return path
if __name__=='__main__':
# To define initial status of the maze and relevant variables.
row = len(maze)
clmn = len(maze[0])
flag = {}
path = {}
stc = Stack([])
stc.push((0,0))
plan = 0
paths = walk(0,0)
# sort the paths according the steps needed, and output them.
sorted_paths = sorted(paths.items(),key = lambda item:len(item[1]))
for p in sorted_paths:
print(p)
optimal_path = sorted_paths[0][1]
print('There are %s paths to the target. The shortest path include %s steps %s'%(len(paths),len(optimal_path)-1,optimal_path))

以上是关于算法:深度优先搜索之迷宫寻径的主要内容,如果未能解决你的问题,请参考以下文章

走迷宫之广度优先搜索

[算法与数据结构] 走迷宫问题(广度与深度优先搜索)

深度优先搜索

算法浅谈——走迷宫问题与广度优先搜索

走迷宫之深度优先搜索

深度优先搜索解决迷宫问题