1. 程式人生 > >經典演算法python程式碼實現

經典演算法python程式碼實現

之前學演算法經常不求甚解,懶癌發作不敲程式碼不實踐,到頭來自己挖的坑還是得自己填,我會陸續更新程式碼,本文大量程式碼來自網際網路,能找到出處的我會盡量貼上出處

廣度優先搜尋、深度優先搜尋

class graph():
    def __init__(self,*arg,**kwargs):
        self.node_neighbors={}
        self.visited={}

    def add_nodes(self,nodelist):
        for node in nodelist:
            self.add_node(node)

    def
add_node(self,node):
if node not in self.node_neighbors.keys: self.node_neighbors[node]=[] def add_edge(self,edge): u,v=edge if (u not in self.node_neighbors[v]) and (v not in self.node_neighbors[u]): self.node_neighbors[u].append(v) if
u!=v: self.node_neighbors[v].append(u) def depth_first_search(self,root=None): self.visited={} order=[] def dfs(n): self.visited[n]=True order.append(n) for node in self.node_neighbors[n]: if node not in
self.visited: dps(node) if root: dps(root) for n in self.node_neighbors.keys: if n not in self.visited: dps(n) print(order) return order def breadth_first_search(self,root=None): self.visited={} order=[] queue=[] def bfs(): while(len(queue)>0): node = queue.pop(0) self.visited[node]=True for n in self.node_neighbors[node]: if not n in self.visited and not n in queue: order.append(n) queue.append(n) if root: queue.append(root) order.append(root) bfs() for node in self.nodes(): if not node in self.visited: queue.append(node) order.append(node) bfs() print (order) return order if __name__ == '__main__': g = Graph() 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.node_neighbors) order = g.breadth_first_search(1) order = g.depth_first_search(1)