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程序设计有所帮助。

相关文章

Django基础三之视图函数的使用方法

Django基础三之视图函数的使用方法

一 Django的视图函数view 一个视图函数(类),简称视图,是一个简单的Python 函数(类),它接受Web请求并且返回Web响应。 响应可以是一张网页的HTML内容,一个重定向...

python把数组中的数字每行打印3个并保存在文档中的方法

python把数组中的数字每行打印3个并保存在文档中的方法

如下所示: arrs=[2,15,48,4,5,6,7,6,4,1,2,3,6,6,7,4,6,8] f=open('test.txt','w+') count=0 for temp...

Python访问MySQL封装的常用类实例

本文实例讲述了Python访问MySQL封装的常用类。分享给大家供大家参考。具体如下: python访问mysql比较简单,下面整理的就是一个很简单的Python访问MySQL数据库类。...

学习python可以干什么

python是什么? python的中文名称是蟒蛇,是一种计算机程序设计语言;是一种动态的、面向对象的脚本语言。最初是用来编写自动化脚本的,随着版本的不断更新和语言新功能的添加,越来越多...

使用IDLE的Python shell窗口实例详解

使用IDLE的Python shell窗口实例详解

启动IDLE后会打开Python shell窗口。当键入代码 时,它会基于Python语法提供自动缩进和代码着色功能。 使用IDLE中的Python shell。代码在输入时会自动着...