깊이 우선 과 넓이 우선 Python 구현

#coding=utf-8 
class Gragh():
    def __init__(self,nodes,sides):
        '''
        nodes    
        sides    

        '''
        # self.sequense   ,key  ,value  key     
        self.sequense = {}
        # self.side     ,               
        self.side=[]
        for node in nodes:
            for side in sides:
                u,v=side
                #               ,                ,         self.side 
                if node ==u:
                    self.side.append(v)
                elif node == v:
                    self.side.append(u)
            self.sequense[node] = self.side
            self.side=[]
        #print self.sequense


    '''
    # Depth-First-Search 
              ,                。            ,           。
           v          ,          v         。
                                 。            ,
                           ,                    。      。        
    '''
    def DFS(self,node0):
        #queue      ,             
        #order             
        queue,order=[],[]
        #            queue ,            
        queue.append(node0)
        while queue:
            # queue pop  v,   v      ,        pop ,      order 
            #          ,pop()      ,     for          ,         ,
            #                     
            v = queue.pop()
            order.append(v)
            #      v    
            for w in self.sequense[v]:
                #w    queue    order,           ,      queue ,        
                if w not in order and w not in queue: 
                    queue.append(w)
        return order

    '''
     readth-First-Search
     BFS       ,            。          ,     。
                        open-closed 。
    '''
    def BFS(self,node0):
        #queue      ,             
        #order             
        queue,order = [],[]
        #            queue ,            
        #        ,                 ,    
        queue.append(node0)
        order.append(node0)
        while queue:
            #queue.pop(0)            ,      ,    for     v      
            #  queue ,  queue.pop(0)                      ,         
            v = queue.pop(0)
            for w in self.sequense[v]:
                if w not in order:
                    #       order.append(w)                      ,    
                    #  self.sequense[v]         order
                    order.append(w)
                    queue.append(w)
        return order




def main():  
    nodes = [i+1 for i in xrange(8)]

    sides=[(1, 2),
        (1, 3),
        (2, 4),
        (2, 5),
        (4, 8),
        (5, 8),
        (3, 6),
        (3, 7),
        (6, 7)]
    G = Gragh(nodes,sides)
    print G.DFS(1)
    print G.BFS(1)
    print G.DFS1(1)

if __name__ == "__main__":
    main() 

좋은 웹페이지 즐겨찾기