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. Maven在Windows上的安装与配置

    下载Maven 1.进入Maven官网下载:maven.apache.org(点击进入或复制浏览器地址栏,回车进入) 注意事项:需要大家要注意的是(截至目前2015年12月1日)最新版本的Maven3 ...

  2. 使用虚拟信用卡认证openshift铜牌计划

    "铜牌计划(bronze)"是OpenShift推出的一项免费计划,这个计划能为你提供更多的免费便利,主要就是可以自己绑域名加SSL证书和应用即使24小时没人访问也不关机了.说这个 ...

  3. Python将MySQL表数据写入excel

    背景:将mysql表查询结果写入excel. 1.使用sqlyog工具将查询结果导出到Excel.xml中,用excel打开发现:因为text字段中有回车换行操作,显示结果行是乱的. 2.用mysql ...

  4. (企业面试部分)超详细思路讲解SQL语句的查询实现,及数据的创建。

    企业面试部分详细的SQL问题,思路讲解 第一步:创建数据库表,及插入数据信息 --Student(S#,Sname,Sage,Ssex) 学生表 CREATE TABLE student( sno ) ...

  5. MySQL调优系列基础篇

    前言 有一段时间没有写博客了,整天都在忙,上班,录制课程,恰巧最近一段时间比较清闲,打算弄弄MYSQL数据库. 关于MySQL数据库,这里就不做过多的介绍,开源.免费等特性深受各个互联网行业喜爱,尤其 ...

  6. WebService 实例

    使用Java WebService API实现 1.服务端接口: package com.h3c.itac.webservice; import javax.jws.WebService; @WebS ...

  7. cocoapods降级版本

    1.卸载当前版本sudo gem uninstall cocoapods 2.下载旧版本sudo gem install cocoapods -v 0.39.0 PS: 如果之前装有多版本,执行1之后 ...

  8. shell脚本的执行

    shell脚本有两种执行方式,一种是直接执行,一种是使用$source 或.命令执行 直接执行 直接执行shell脚本,bash会在当前bash下新建一个子bash进程用来执行shell脚本,此时脚本 ...

  9. x01.Lab.StoreApp: XP 停服,微软变脸

    变脸,川剧的一种表演形式,除了哄哄小孩,似乎别无用处.而川剧变脸从业者何其多也,存在时间何其长也.以如此多的从业者,如此长的时间,来进行科研,其成果一定是斐然吧.推而广之,试问天下谁能敌! 微软变脸, ...

  10. mysqli,Fatal error

    <?php //mysql数据库类-mysqli版 //2014/6/13 class mysqlidb{ public $dbhost; public $dbuser; public $dbp ...