1. 程式人生 > >圖的深度優先搜尋和廣度優先搜尋-python實現

圖的深度優先搜尋和廣度優先搜尋-python實現


            
            
                    
    
            
                
            
 參考程式碼:https://www.cnblogs.com/yupeng/p/3414736.html    

# -*- coding: utf-8 -*-
"""
Created on Tue Apr 10 20:58:23 2018

@author: Lenovo
"""

class Graph(object):
    def __init__(self):
        self.node_neighbors={}
        self.visited=[]
    
    def add_nodes(self,nodelist):
        for n in nodelist:
            if n not in self.nodes():
                self.node_neighbors[n]=[]
            else:
                print("repeat element")
                return
    
    def add_edge(self,edge):
        u,v=edge
        if v not in self.node_neighbors[u]:
            if v!=u:
                self.node_neighbors[u].append(v)
            else:
                print("pointing to itself is not allowed")
     
    def nodes(self):
        return self.node_neighbors.keys()
    
    def print_tree(self):
        print(self.node_neighbors)
        
    def breadth_first_search(self,root):
        queue=[]
        self.visited=[]
        order=[]
        def bfs():
            if len(queue)>0:
                node=queue.pop(0)
                self.visited.append(node)
                for n in node.neighbors[node]:
                     if (n not in queue) and(n not in self.visited):
                         queue.append(n)
                         order.append(n)
                bfs()
                
        if root:
            queue.append(root)
            order.append(root)
            self.visited.append(root)
            
        for n in self.nodes():
            if n not in self.visited:
                queue.append(n)
                order.append(n)
                
        print(order)
        return
    
    def depth_first_search(self,root=None):
        self.visited=[]
        order=[]
        def dfs(node):
            #white->grey
            for n in self.node_neighbors[node]:
                if(n not in self.visited):
                    order.append(n)
                    dfs(n)
            #grey->black
            self.visited.append(node)
            
        if root:
            order.append(root)
            dfs(root)
            
        for n in self.nodes():
            if n not in self.visited:
                dfs(n)
            
        print(order)
        return
    
if __name__=='__main__':
    g= Graph()#python 中建立一個類的物件
    g.add_nodes([i+1 for i in range(8)])
    g.add_edge((1, 2))
    g.add_edge((1, 3))
    g.add_edge((2, 4))
    g.add_edge((2, 5))
    g.add_edge((4, 8))
    g.add_edge((5, 8))
    g.add_edge((3, 6))
    g.add_edge((3, 7))
    g.add_edge((6, 7))
    
    print("nodes:",g.nodes())
    print(g.print_tree())
    
    order=g.depth_first_search(1)
    order=g.breadth_first_search(1)
 
                
            
            
                    
    
            
                
            
        

結果:

nodes: [1, 2, 3, 4, 5, 6, 7, 8]

廣度優先:
[1, 2, 3, 4, 5, 6, 7, 8]

深度優先:

[1, 2, 4, 8, 5, 3, 6, 7]