python数据结构之图的实现方法

yipeiwu_com6年前Python基础

本文实例讲述了python数据结构之图的实现方法。分享给大家供大家参考。具体如下:

下面简要的介绍下:

比如有这么一张图:

    A -> B
    A -> C
    B -> C
    B -> D
    C -> D
    D -> C
    E -> F
    F -> C

可以用字典和列表来构建

graph = {'A': ['B', 'C'],
       'B': ['C', 'D'],
       'C': ['D'],
       'D': ['C'],
       'E': ['F'],
       'F': ['C']}

找到一条路径:

def find_path(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
      return path
    if not graph.has_key(start):
      return None
    for node in graph[start]:
      if node not in path:
        newpath = find_path(graph, node, end, path)
        if newpath: return newpath
    return None

找到所有路径:

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

找到最短路径:

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

希望本文所述对大家的Python程序设计有所帮助。

相关文章

python3实现elasticsearch批量更新数据

废话不多说,直接上代码! updateBody = { "query":{ "range":{ "write_date": { "g...

Python面向对象封装操作案例详解

Python面向对象封装操作案例详解

本文实例讲述了Python面向对象封装操作。分享给大家供大家参考,具体如下: 目标 封装 小明爱跑步 存放家具 01. 封装 封装 是面向对象编程的一大特点 面向对象编程的 第一步 ——...

Python实现判断并移除列表指定位置元素的方法

Python实现判断并移除列表指定位置元素的方法

本文实例讲述了Python实现判断并移除列表指定位置元素的方法。分享给大家供大家参考,具体如下: 问题很简单,输入一个列表和索引,若索引超出列表范围则返回源列表,否则删除指定索引位置的元...

Django中自定义查询对象的具体使用

自定义查询对象 - objects ①声明一个类EntryManager,继承自models.Manager,并添加自定义函数 ②使用创建的自定义类EntryManager 覆盖Mo...

python获取文件真实链接的方法,针对于302返回码

使用模块requests 方式代码如下: import requests url_string="https://******" r = requests.head(url_st...