数据结构之图:DFS、BFS
深度优先搜索:走到走不下去为止(迷宫问题),需要标记已经走过的节点。
1 def dfsIterative(G, start, dest): 2 stack = [] # vertex 3 visited = set() # vertex id 4 parent = {} # vertex id 5 stack.append(start) 6 while len(stack) != 0: 7 curr = stack.pop() # vertex 8 print("visiting ", curr.getVertexID()) 9 if (curr.getVertexID() == dest.getVertexID()): 10 return parent 11 neighbors = G.getNeighbors(curr.getVertexID()) 12 for n in neighbors: 13 id = n.getVertexID() 14 if id in visited:continue 15 visited.add(id) 16 parent[id] = curr.getVertexID() 17 stack.append(n) 18 return None
1 def dfs(G, currentVert, visited): 2 visited[currentVert] = True # mark the visited node 当前节点 3 print("traversal: " + currentVert.getVertexID()) 4 for nbr in currentVert.getConnections(): # take a neighbouring node 5 if nbr not in visited: # condition to check whether the neighbour node is already visited 6 dfs(G, nbr, visited) # recursively traverse the neighbouring node 7 return 8 9 def DFSTraversal(G): 10 visited = {} # Dictionary to mark the visited nodes 11 for currentVert in G: # G contains vertex objects 12 if currentVert not in visited: # Start traversing from the root node only if its not visited 13 dfs(G, currentVert, visited) # For a connected graph this is called only onc
广度优先搜索(BFS:Breadth-First Search):警察抓小偷,设定一个搜索范围,在这个搜索范围没有搜索到之后,再去扩大搜索范围。一步能走到的地方-->两步-->三步-->四步......
把Stack改为Queue即可
1 from collections import deque 2 def bfs(G, start, dest): 3 queue = deque() # vertex 4 visited = set() # vertex id 5 parent = {} # vertex id 6 queue.append(start) 7 while len(queue) != 0: 8 curr = queue.popleft() # vertex 9 print("visiting ", curr.getVertexID()) 10 if (curr.getVertexID() == dest.getVertexID()): 11 return parent 12 neighbors = G.getNeighbors(curr.getVertexID()) 13 for n in neighbors: 14 id = n.getVertexID() 15 if id in visited:continue 16 visited.add(id) 17 parent[id] = curr.getVertexID() 18 queue.append(n) 19 return None