class Graph(object):

    def __init__(self,*args,**kwargs):
self.node_neighbors = {}
self.visited = {} def add_nodes(self,nodelist): for node in nodelist:
self.add_node(node) def add_node(self,node):
if not node in self.nodes():
self.node_neighbors[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):
order = [] if root:
self.dfs(root, order) for node in self.nodes():
if not node in self.visited:
self.dfs(node, order) print(order)
return order def dfs(self, node, order):
self.visited[node] = True
order.append(node)
for n in self.node_neighbors[node]:
if not n in self.visited:
self.dfs(n) # 广度优先
def breadth_first_search(self, root=None):
queue = []
order = [] if root:
queue.append(root)
order.append(root)
self.bfs(queue, order) for node in self.nodes():
if not node in self.visited:
queue.append(node)
order.append(node)
self.bfs(queue, order)
print(order) return order def bfs(self, queue, order):
while len(queue)> 0:
node = queue.pop(0) self.visited[node] = True
for n in self.node_neighbors[node]:
if (not n in self.visited) and (not n in queue):
queue.append(n)
order.append(n) # 找一条路径
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 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))
print("nodes:", g.nodes()) order = g.breadth_first_search(1)
order = g.depth_first_search(1)

python 图的更多相关文章

  1. PySide——Python图形化界面

    PySide——Python图形化界面 PySide——Python图形化界面入门教程(四) PySide——Python图形化界面入门教程(四) ——创建自己的信号槽 ——Creating Your ...

  2. PySide——Python图形化界面入门教程(四)

    PySide——Python图形化界面入门教程(四) ——创建自己的信号槽 ——Creating Your Own Signals and Slots 翻译自:http://pythoncentral ...

  3. PySide——Python图形化界面入门教程(六)

    PySide——Python图形化界面入门教程(六) ——QListView和QStandardItemModel 翻译自:http://pythoncentral.io/pyside-pyqt-tu ...

  4. PySide——Python图形化界面入门教程(五)

    PySide——Python图形化界面入门教程(五) ——QListWidget 翻译自:http://pythoncentral.io/pyside-pyqt-tutorial-the-qlistw ...

  5. PySide——Python图形化界面入门教程(三)

    PySide——Python图形化界面入门教程(三) ——使用内建新号和槽 ——Using Built-In Signals and Slots 上一个教程中,我们学习了如何创建和建立交互widget ...

  6. PySide——Python图形化界面入门教程(二)

    PySide——Python图形化界面入门教程(二) ——交互Widget和布局容器 ——Interactive Widgets and Layout Containers 翻译自:http://py ...

  7. PySide——Python图形化界面入门教程(一)

    PySide——Python图形化界面入门教程(一) ——基本部件和HelloWorld 翻译自:http://pythoncentral.io/intro-to-pysidepyqt-basic-w ...

  8. Python 图_系列之基于<链接表>实现无向图最短路径搜索

    图的常用存储方式有 2 种: 邻接炬阵 链接表 邻接炬阵的优点和缺点都很明显.优点是简单.易理解,对于大部分图结构而言,都是稀疏的,使用炬阵存储空间浪费就较大. 链接表的存储相比较邻接炬阵,使用起来更 ...

  9. 安装Python图型处理库Python Imaging Library(PIL)

    方法1: 在Debian/Ubuntu Linux下直接通过apt安装: $sudo apt-get install python-imaging Mac和其他版本的Linux可以直接使用easy_i ...

  10. python 图实现

    #coding:utf-8 __author__ = 'similarface' class Graph: def __init__(self,label,extra=None): #节点是类实例 s ...

随机推荐

  1. MVC6的内置ActionResult类型

    BadRequestObjectResult,BadRequestResult http 400 bad request ChallengeResult   ContentResult   Creat ...

  2. CentOS系统启动流程你懂否

    一.Linux内核的组成 相关概念: Linux系统的组成部分:内核+根文件系统 内核:进程管理.内存管理.网络协议栈.文件系统.驱动程序. IPC(Inter-Process Communicati ...

  3. stm32 加入 USE_STDPERIPH_DRIVER、STM32F10X_HD的原因

    初学STM32,在RealView MDK 环境中使用STM32固件库建立工程时,初学者可能会遇到编译不通过的问题.出现如下警告或错误提示: warning: #223-D: function &qu ...

  4. win7下Qt5使用mysql C++编程配置

    先下载mysql的库文件链接:http://files.cnblogs.com/files/xiaobo-Linux/mysql.zip 把两个文件放入 Qt目录\Qt5.5.0\5.5\mingw4 ...

  5. mybatis 插入数据时返回主键

    在使用MyBatis做持久层时,insert语句默认是不返回记录的主键值,而是返回插入的记录条数:显然,假如主键是你生成后插入的,自然你已经有主键了,显然不需要我们再去获得,所以我们这里处理的是当主键 ...

  6. Redhat使用CentOS的Yum 网络源

    Redhat 的更新包只对注册的用户生效,所以我们自己手动更改成CentOS 的更新包,CentOS几乎和redhat是一样的. 1.首先查看redhat 7.0系统本身所安装的那些yum 软件包:[ ...

  7. stm32之NVIC

    非本人原创,转载自http://blog.csdn.net/denghuanhuandeng/article/details/8350392 STM32的NVIC理解 例程:  /* Configur ...

  8. 【转帖】4412ARM开发板学习笔记(一)

    本文转自迅为论坛:http://www.topeetboard.com 新手在进行开发学习前,建议先看01-迅为电子开发板入门视频.对开发板和开发环境有一定的了解后,不要盲目接线开机.以下是个人的一点 ...

  9. VMworld 2015 感受:VMware “Ready For Any”

    今年有机会参加在旧金山举行的 VMworld 2015.今天是正式开始的第一天.争取每天写一篇文章分享所见所听所感.第一天的主要活动,包括上午的 General Session,由 VMware 的几 ...

  10. [转]ASP.NET MVC 3 Razor + jqGrid 示例

    本文转自:http://www.cnblogs.com/think8848/archive/2011/07/15/2107828.html 前些天写了一篇有关jqGrid的文章,因为是公司项目的原因一 ...