使用邻接矩阵在python中查找路径

时间:2014-11-07 04:21:43

标签: python python-2.7 path-finding

我的程序出现问题,这是我的代码:

graph=  [#a,b,c,d,e,f,g,h,i,j
     [0,1,1,1,1,0,0,0,0,0],  #a
     [1,0,0,1,0,0,1,0,0,0],  #b
     [1,0,0,1,0,0,0,0,0,0],  #c
     [1,1,1,0,0,0,0,1,0,0],  #d
     [1,0,0,0,0,1,0,1,1,0],  #e
     [0,0,0,0,1,0,0,1,1,0],  #f
     [0,1,0,0,0,0,0,1,1,1],  #g
     [0,0,0,1,1,1,1,0,1,0],  #h
     [0,0,0,0,1,1,1,1,0,1],  #i
     [0,0,0,0,0,0,1,0,1,0],  #j
    ]
nodes='ABCDEFGHIJ'
a=raw_input('Source Destination = ')
b=raw_input('Destination = ')
p=[[a]]
flag=0

while len(p)>0 and flag==0:
 x=p.pop(0)
 j=nodes.index(x[len(x)-1])
 for i in range(0,10):
    if graph[j][i]==1 and nodes[i]==b:
        x.append(nodes[i])
        print x
        flag=1
    elif graph[j][i]==1:
        if not(nodes[i] in x):
            temp=x
            temp.append(nodes[i])
            p.append(temp)
 print p

例如,我使用I作为我的srcA作为我的dest。 在第一个p,它打印

[[I, E, F, G, H, J],
 [I, E, F, G, H, J],
 [I, E, F, G, H, J],
 [I, E, F, G, H, J],
 [I, E, F, G, H, J]]

但我期待的是[[I,E],[I,F],[I,G],[I,H],[I,J]]

1 个答案:

答案 0 :(得分:0)

问题在于您将元素添加到队列路径的方式:

if not(nodes[i] in x):
    temp = x
    temp.append(nodes[i])
    p.append(temp)

这样,temp 将成为x的副本,而是引用。因此,无论何时将节点附加到temp,您都会将其附加到x,从而附加到所有之前和之后的temp。你必须复制一份:

    temp = x[:] # slice of `x` from first to last element -> copy

您可以在代码中改进一些内容。这是我的版本:

while p:                          # evaluates to true if p not empty
    x = p.pop(0)
    j = nodes.index(x[-1])        # use [-1] to get last element
    if nodes[j] == b:             # by moving this check out of the loop...
        print "Path found:", x    # (don't forget to print the path)
        break                     # ...you can use break and don't need flag
    for i, e in enumerate(nodes): # enumerate gives (index, element)
        if graph[j][i] and e not in x: # a bit more concise
            p.append(x + [e])     # this way, we don't need temp at all