繁体   English   中英

在python中优化广度优先搜索

[英]optimizing breadth first search in python

我编写了深​​度优先搜索,该搜索将返回找到目标节点的深度,如果没有找到路径,则返回-1。 该算法有效,但我需要加快速度。 这是功能

def depth(dic, head, target):
    if(head==target):
        return
    depth=1
    que = deque()
    que.append('|') #used to mark end of each breadth so i can count depth correctly
    used = list()
    add = True

    while(que): #while the que isn't empty
        for x in dic[head]: #check current level
            if x==target:
                print(depth),
                return;
        for x in dic[head]: #add this level to the que and used list
            for y in used:
                if y==x:
                    add=False
                    break
            if add == True:
                que.append(x)
                used.append(x)
            add=True
        que.append('|') #add our delimiter
        while(que): #grab the next item from the que and inc depth count
            temp = que.popleft()
            if temp=='|': #bump depth counter since we found end of a level
                depth+=1
            else:
                head=temp #bump to next node to check
                break

    print('-1'), #reached the end, node not found

传入的dic被声明

dic = defaultdict(list)

这样每个值都是一个整数列表,而我正在使用| 所以我知道什么时候撞深度计 我意识到自己陷入了中间,在那里我正在检查当前级别的所有节点并将它们添加到que和used列表中,但是我无所适从地加快了速度。

编辑:

对于这里遇到类似问题的人,我最终使用的算法来说,它执行搜索的方式有些奇怪,因为我返回的是可以找到值的最浅深度,如果不是,则返回所有连接。在同一时间检查了相同的深度,我们最终可能找到下一个深度的节点(例如因一个错误而偏离)

def depthOfNodeBFS(dic, head, target):
    if(head==target):
        return
    depth=0
    que = []
    que.append(head)
    used = set()
    nex = list()

    while(que): #while the que isn't empty
        depth+=1 #bump the depth counter
        for x in que: #check the next level of all nodes at current depth
            if target in dic[x]: #if the target is found were done
                print(depth),
                return;
            else:               #other wise track what we've checked
                nex.append(x)
                used.add(x)
        while(nex):       #remove checked from que and add children to que
            que.pop(0)
            que.extend(dic[nex.pop()]-used)
    print('-1'),

在我看来,这看起来更像广度优先搜索,而不是深度优先搜索,但是您不应该嵌套while循环。 广度优先搜索的常用算法如下:

add the root to the queue
while the queue is not empty:
  dequeue the first element elt
  if elt is the solution, return it
  otherwise, add each child of elt to the queue

如果要报告深度,我建议向队列添加元组(节点,深度):

add (root, 0) to the queue
while the queue is not empty:
  elt, depth = queue.popleft()
  if elt is the solution, return (elt, depth)
  otherwise, for each child of elt:
     add (child, depth+1) to the queue

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM