图的遍历


# __* coding = utf-8 *__

class Graph:
    def __init__(self):
        self.node_neighbors = {}

    def add_node(self,node):
        if not self.node_neighbors.get(node):
            self.node_neighbors[node] = []

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

    def add_edge(self,edge):
        u,v = edge
        if (v not in self.node_neighbors[u]) and (u not in self.node_neighbors[v]):
            self.node_neighbors[u].append(v)
        if u != v:
            self.node_neighbors[v].append(u)

    def nodes(self):
        return self.node_neighbors.keys()


    def depth_first_search(self, root=None):
        '''
            递归方式,深度优先遍历
        '''
        visited = []
        order = []

        def dfs(root=None):
            if root:
                order.append(root)
                visited.append(root)
                for u in self.node_neighbors[root]:
                    if  u not in visited:
                        dfs(u)
        if root:
            dfs(root)
            return order
        else:
            return None

    def depth_first_search2(self,root=None):
        '''
            深度优先遍历,迭代方式
            1. 判断节点是否为None
            2. 判断当前节点是否有孩子,有则访问孩子节点,循环步骤1,孩子节点入站
            3. 没有孩子节点,出栈,循环步骤1
        '''
        visited = []
        order = []
        s = []
        s.append(root)
        visited.append(root)
        order.append(root)
        while root:

            root = self._getChild(root, visited)

            if not root:
                s.pop()
                if len(s) > 0:
                    root = s[len(s) - 1]
            else:
                s.append(root)
                visited.append(root)
                order.append(root)



        return order

    def _getChild(self,root,visited):
        for node in self.node_neighbors[root]:
            if node not in visited:
                return node
        return None

    def breadth_first_search(self, root=None):

        '''
            广度优先遍历,利用队列,保存每一层的节点
        '''
        visited = []
        order = []
        queue = []

        queue.append(root)
        while len(queue) > 0:
            v = queue.pop(0)
            visited.append(v)
            order.append(v)
            for u in self.node_neighbors[v]:
                if u not in visited and u not in queue:
                    queue.append(u)
        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))
    g.add_edge((1,5))
    # g.add_edge((5,6))
    print "nodes:", g.nodes()

    print g.depth_first_search(1)
    print g.breadth_first_search(1)
    print g.depth_first_search2(1)

你可能感兴趣的:(数据结构与算法)