python实现:求两点间的所有路径

python实现:求两点间的所有路径

  • 0.引言
  • 1.求两点间的所有路径算法

0.引言

本篇blog以及接来了几篇都是补上个学期算法课的几个基础课程实验,由于已经过了大半年了,记不太清是怎么证明了,故直接奉上代码,不多赘述。

1.求两点间的所有路径算法

# 测试数据
8
5
A B
A C
A E
B E
B D
C E
C F
E F
A
E
"""defgraph.py"""

'''
class Vertex(object):
    def __init__(self,name):
        self.name = name
        self.adjs = []
        self.adjsname = []
        self.isdestn = 0
    
    def look_adjs(self):
        L = []
        for v in self.adjs:
            L.append(v.name)
        print(L)

class Edge(object):
    def __init__(self,v,u):
        self.relevances = {v.name:v.adjs, u.name:u.adjs}

    def look_relevances(self):
        L = []
        for vname in self.relevances.keys():
            L.append(vname)
        print(L)

'''
class Graph(object):
    '''undirected unweighted graph'''

    def __init__(self):
        self.VertexNumber = int(0)
        self.EdgeNumber = int(0)
        self.VertexSet = {}
        self.EdgeSet = []
        self.origin = None
        self.destn = None
        self.O2DPathNum = int(0)
    
    def insert_vertex(self,vertex):
        self.VertexSet.setdefault(vertex,[])

    def insert_edge(self,v,u):
        edge = set([v, u])
        if not (edge in self.EdgeSet):
            self.EdgeSet.append(edge)

        '''establish adjacency relationship'''
        if not (u in self.VertexSet[v]):
            self.VertexSet[v].append(u)
        if not (v in self.VertexSet[u]):
            self.VertexSet[u].append(v)

    def get_adjs(self,vertex):
        if vertex in self.VertexSet.keys():
            return self.VertexSet[vertex]
        else:
            print('{} is not in VertexSet'.format(vertex))  

    def look_VertexSet(self):
        L = []
        for v in self.VertexSet.keys():
            L.append(v)    
        print(L)
    
    def look_EdgeSet(self):
        print(self.EdgeSet)
'''All paths of two vertexs.py'''

import string
from defgraph import *

def initialize_graph(G):
    with open('test-5.txt','r') as f:
        G.EdgeNumber = int(f.readline().strip())
        G.VertexNumber = int(f.readline().strip())
        
        '''
        create the EdgeSet and the VertexSet
        notes:enumerate can get the loop count'
        '''
        for i,line in enumerate(f.readlines()):
            if  i == G.EdgeNumber:
                G.origin = line.strip()
            elif i == G.EdgeNumber + 1:
                G.destn = line.strip()
            else:
                u,v = line.strip().split()
            
                G.insert_vertex(v)
                G.insert_vertex(u)

                G.insert_edge(v,u)


def search_path():
    global path
    path = []
    path.append(G.origin)
    visit(G.origin)
    print("Path Number:{}".format(G.O2DPathNum))

def visit(vertex):
    v_adjs = G.get_adjs(vertex) 

    '''whether vertex has adjacences'''
    if v_adjs:
        for u in v_adjs:
            if u == G.destn:
                print(''.join([v for v in path]) + u) 
                G.O2DPathNum += 1
            elif not (u in path):
                path.append(u)
                visit(u)
        '''loop end means that node 'u' has been explored'''
        path.pop()


def main():
    global G
    G = Graph()
    initialize_graph(G)
    '''
    G.look_VertexSet()
    G.look_EdgeSet()
    print(G.get_adjs('A')) 
    '''
    search_path()
    

if __name__ == "__main__":
    main()

你可能感兴趣的:(课程实验)