两个节点间最短路径

class Graphic:
    def __init__(self):
        self.edges={}
    
    def join(self, a, b):
        if self.edges.has_key(a):
            self.edges[a]+=[b]
        else:
            self.edges[a]=[b]
        if self.edges.has_key(b):
            self.edges[b]+=[a]
        else:
            self.edges[b]=[a]
    
    def test(self, a, b):
        q=[]
        q.append(a)
        reaches={a:[]}
        while len(q) > 0:
            cur=q.pop(0)
            for n in self.edges[cur]:
                if n==cur:
                    continue
                if reaches.has_key(n) and len(reaches[n]) <= len(reaches[cur])+1:
                    continue
                if reaches.has_key(b) and len(reaches[b]) <= len(reaches[cur])+1:
                    continue
                q.append(n)
                reaches[n]=reaches[cur]+[cur]
        return reaches[b]+[b]

g=Graphic()

g.join(‘a’, ‘b’)
g.join(‘a’, ‘e’)
g.join(‘b’, ‘c’)
g.join(‘e’, ‘k’)
g.join(‘j’, ‘k’)
g.join(‘j’, ‘c’)
g.join(‘j’, ‘h’)
g.join(‘j’, ‘z’)
g.join(‘c’, ‘d’)
g.join(‘d’, ‘f’)
g.join(‘f’, ‘l’)
g.join(‘z’, ‘l’)

print g.test(‘a’,’d’)

2 thoughts on “两个节点间最短路径

  1. 姚姚鼠 April 27, 2006 / 9:58 am

    又是一大堆看不懂的東西,你會MATLAB嗎,會的話幫我解決一下我畢業設計的一些問題。

  2. fengfeng April 26, 2006 / 12:05 pm

    蛙 这个是什么程序呀

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s