广度优先搜索深度优先搜索的Python代码

时间:2020-03-09 11:52:27

标签: python

我编写了一些代码,这些代码在定义图形时执行BFS。我现在需要编辑代码来执行DFS,有人知道我需要更改以完成此操作吗?

这是我现在拥有的BFS代码:

class MyQUEUE: # Just an implementation of a queue.
def __init__(self): # Initialises the queue to an empty queue.
    self.holder = []

def enqueue(self,val):
# Appends item val onto the end of the queue.
    self.holder.append(val)

def dequeue(self):
    # Pops the head off the queue and returns it value.
    val = None
    try:
        val = self.holder[0]
        if len(self.holder) == 1:
            self.holder = []
        else:
            self.holder = self.holder[1:]
    except:
            pass
    return val

def IsEmpty(self):
    # Returns True if the queue is empty.
    result = False
    if len(self.holder) == 0:
        result = True
return result


def BFS(graph,start,end):
# Traverses the graph using a Breadth First Search starting
# from the start node with end being the goal node. Uses a
# queue to store the nodes that are current leaves at the
# fringe of the search.

q = MyQUEUE() # make an empty queue first
q.enqueue([start]) # add the start node onto the queue
while q.IsEmpty() == False:
    path = q.dequeue()
    last_node = path[len(path)-1]
    print (path)
    if last_node == end:
        print ("VALID_PATH : ", path)
    for link_node in graph[last_node]:
        if link_node not in path:
            new_path = []
            new_path = path + [link_node]
            q.enqueue(new_path)

1 个答案:

答案 0 :(得分:4)

代替添加-在开头插入:

修改:

self.holder.append(val)

收件人:

self.holder.insert(0, val)

说明

当BFS“逐层丸”邻居时,DFS“一直到底部”再返回。实际上,通过更改顺序(递归地)迭代邻居,可以将BFS修改为DFS。

更新

正如Kaya在下面评论的那样,如果我们关心性能,则应该使用append / pop而不是insert,因为insert的花费为O(n),而append / pop的花费为O(1)