有向图的邻接表Python表示形式

使用邻接表表示有向图,并且使用回溯法查找有向图中的路径
对于有向图的邻接表表示形式,可以使用字典数据结构来表示

import sys
class Solution:
    def __init__(self):
        # self.graph = {'A':['B','C'],
        #               'B':['C','D'],
        #               'C':['D'],
        #               # 'D':['C'],
        #               'E':['F'],
        #               'F':['C']
        # }
        self.graph = {
            '1':['3','4'],
            '2':['5','4'],
            '3':['6'],
            '4':['3','7','6'],
            '5':['7','4'],
            '7':['6']
        }
    def find_path(self,start,end,path=[]):
        path = path+[start]
        if start==end:
            return path
        if not self.graph.has_key(start):
            return None
        for node in self.graph[start]:
            if node not in path:
                newpath = self.find_path(node,end,path)
                if newpath:
                    return newpath
        return None

    def find_paths(self,start,end,path=[]):
        path = path+[start]
        # path.append(start)
        paths=[]
        if start==end:
            return [path]
        if not self.graph.has_key(start):
            return None
        paths = []
        for node in self.graph[start]:
            if node not in path:
                newpath = self.find_paths(node,end,path)
                if newpath:
                    paths=paths + newpath
        return paths

    def find_shortest_path(self,start,end,path=[]):
        path = path+[start]
        # path.append(start)
        paths=[]
        if start==end:
            return path
        if not self.graph.has_key(start):
            return None
        shortest = None
        for node in self.graph[start]:
            if node not in path:
                newpath = self.find_shortest_path(node,end,path)
                if newpath:
                    if not shortest or len(shortest)>len(newpath):
                        shortest = newpath
        return shortest

    def dfs(self):
        stack = []
        visited = set()
        for key in self.graph:
            # sys.stdout.write(key+'\n')
            if key not in visited:
                sys.stdout.write(key+" ")
                stack.append(key)
                visited.add(key)
            while len(stack)>0:
                tmp = stack[len(stack)-1]
                if not self.graph.has_key(tmp):
                    if len(stack)>0:
                        stack.pop()
                        continue
                for value in self.graph[tmp]:
                    if value not in visited:
                        sys.stdout.write(value+" ")
                        stack.append(value)
                        visited.add(value)
                    else:
                        if len(stack)>0:
                            stack.pop()
                            continue

    def bfs(self):
        from collections import deque
        queue = deque()
        visited=set()
        for key in self.graph.keys():
            if key not in visited:
                queue.append(key)
                visited.add(key)
            while len(queue)>0:
                tmp = queue.popleft()
                sys.stdout.write(tmp+'\t')
                if not self.graph.has_key(tmp):
                    break
                for value in self.graph[tmp]:
                    if value not in visited:
                        queue.append(value)
                        visited.add(value)


    def has_circle(self):
        from collections import deque
        visited = set()
        for key in self.graph.keys():
            if key not in visited:
                queue = deque(key)
                visited.add(key)
                while len(queue)>0:
                    tmp = queue.popleft()
                    if self.graph.has_key(tmp):
                        for value in self.graph[tmp]:
                            if key==value:
                                print "There is circle"
                                return
                            if value not in visited:
                                visited.add(value)
                                queue.append(value)
        print "There is not circle"
        return
if __name__=="__main__":
    s=Solution()
    sys.stdout.write("Breadth first search:"+'\n')
    s.bfs()
    sys.stdout.write('\n')
    sys.stdout.write("Depth first search:"+'\n')
    s.dfs()
    sys.stdout.write('\n')
    sys.stdout.write("find a path:" + '\n')
    print s.find_path('1','6')
    sys.stdout.write("find all paths:" + '\n')
    print s.find_paths('1','6')
    sys.stdout.write("find the shortest path:" + '\n')
    print s.find_shortest_path('1','6')
    sys.stdout.write("judge circle:" + '\n')
    s.has_circle()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1 概述 图是数据结构中最复杂的形式,也是最烧脑的结构。无数的牛人乐此不疲地钻研,然而,时至今日,依然有很多问题等...
    CodingTech阅读 2,400评论 0 8
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,981评论 19 139
  • 因为之前就复习完数据结构了,所以为了保持记忆,整理了一份复习纲要,复习的时候可以看着纲要想具体内容。 树 树的基本...
    牛富贵儿阅读 7,010评论 3 10
  • 数据结构与算法--拓补排序及无环加权有向图的最短路径 现实生活中一些项目工程、生产开发,都有一个所谓的流程。一个流...
    sunhaiyu阅读 2,357评论 0 8
  • 第一章 绪论 什么是数据结构? 数据结构的定义:数据结构是相互之间存在一种或多种特定关系的数据元素的集合。 第二章...
    SeanCheney阅读 5,822评论 0 19