目录
深度优先检索
1. definition
2. implementation
# Find a path from the start junction to the end junction
# Tree's structure:
# Tree = [ [],[1,2],[2,3],...,[p,q] ] where len(Tree) = n+1
# Note that there is only n junction, and Tree has a [] mean that Tree[i] represents the
# neibouring junctions of i, i=1,2,...,n
def DFS(Tree,start,end):
visited = set([start])
stack = [start]
while len(stack) > 0:
cur = stack.pop()
for node in Tree[cur]:
if node not in visited:
visited.add(node)
stack.extend([cur,node])
break
if stack[-1] == end:
return stack
# Note that if I want all the paths from start to end
# then
# if stack[-1] == end:
# paths.append(stack)
# return paths
宽度优先搜索
1. definition
2. implementation
# Find a path from the start junction to the end junction
# Tree's structure:
# Tree = [ [],[1,2],[2,3],...,[p,q] ] where len(Tree) = n+1
# Note that there is only n junction, and Tree has a [] mean that Tree[i] represents the
# neibouring junctions of i, i=1,2,...,n
# Notion:This function can only find one path from a to b
def BFS(Tree,start,end):
visited = set([start])
queue = [start]
parent = {start:None}
while len(queue) > 0:
cur = queue.pop(0)
for node in Tree[cur]:
if node not in visited:
visited.add(node)
queue.append(node)
parent[node] = cur
# find a path
a = end
path = [end]
while a != start:
a = parent[a]
path.append(a)
path.reverse()
return path