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

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

相关文章

Android模拟器无法启动,报错:Cannot set up guest memory ‘android_arm’ Invalid argument的解决方法

Android模拟器无法启动,报错:Cannot set up guest memory ‘android_arm’ Invalid argument的解决方法

本文实例讲述了Android模拟器无法启动,报错:Cannot set up guest memory ‘android_arm': Invalid argument的解决方法。分享给大...

Python3按一定数据位数格式处理bin文件的方法

Python3按一定数据位数格式处理bin文件的方法

因为研究生阶段经常用MATLAB作图,处理数据,但是MATLAB太过于庞大,不方便,就想用python处理。 问题:我们通常处理的最原始的数据是bin文件,打开后如下所示,是按16进制形...

django实现分页的方法

本文实例讲述了django实现分页的方法。分享给大家供大家参考。具体如下: Python代码如下: #!/usr/bin/env python # -*- coding: utf-8...

Python3实现发送QQ邮件功能(文本)

本文为大家分享了Python3实现发送QQ邮件功能:文本,供大家参考,具体内容如下 注意:使用前需要到qq中设置开启POP3 和IMAP服务和设置第三方授权码 然后在下面打x那里填入相...

pyqt4教程之messagebox使用示例分享

复制代码 代码如下:#coding=utf-8#对话框import sysfrom PyQt4 import QtGui, QtCoreclass Window( QtGui.QWidg...