有关搜索方式模板

 

DFS代码- 递归写法
visited = set()

def dfs(node, visited):
    #terminator
    if node in visited:
        #already visited
        return
    visited.add(node)

    #process current
    ...
    for next_node in node.children():
        if not next_node in visited:
            dfs(next_node, visited)

DFS代码- 非递归写法
def DFS(self, tree):
    if tree.node in None:
        return []
    visited, stack = [], [tree.root]

    while stack:
        node = stack.pop()
        visited.add(node)

        process(node)
        nodes = generate_related_nodes(node)
        stack.push(nodes)
    
    #other processing work
    ...
    
BFS 代码

def BFS(graph,start,end):

    queue = []
    queue.append([start])
    visited.add(start)
    
    while queue:
        node=queue.pop()
        visited.add(node)
        
        process(node)
        nodes=generate_related_nodes(mpde)
        queue.push(nodes)


A* search
def AstarSearch(graph,start,end):
    pq = collections.priority_queue() # 优先级-》 估价函数
    pq.append([start])
    visited.add(start)

    while pq:
        node =pq.pop() # can we add more intelligence here ?
        visited.add(node)
        
        process(node)
        nodes = generate_related_nodes(node)
        unvisited = [node for node in nodes if node not in visited]
        pq.push(unvisited)

 

你可能感兴趣的:(数据结构与算法)