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. jar 命令 打包装class文件的文件夹

    由于将spring源代码导入到eclipse后,缺少jar包,     所以从maven仓库中下载spring发布的spring-core  jar包. 为了方便理解目录结构,使用tree命令: tr ...

  2. jquery bootgrid 一个很好的 数据控件,可用于任何语言

    http://www.jquery-bootgrid.com/Examples#command-buttons 效果很好,http://www.open-open.com/lib/view/open1 ...

  3. PHP延迟静态绑定 static关键字

    示例代码1 abstract class Parent { } class Man extends Parent { public static function create(){ return n ...

  4. SSRS 的简单使用(一)

    简介 SQL Server Reporting Services(SSRS),微软企业级报表平台,和SQL Server Integration Service以及SQL Server Analysi ...

  5. java.lang.NoClassDefFoundError:TagSupport

    这个错误应该就是没有成功加载tomcat自带的jar包jsp-api.jar. 在网上看到很多网友说要把tomcat/lib下的jsp-api.jar拷贝到项目/WEB_INF/lib下并导入,本人试 ...

  6. Stanford coursera Andrew Ng 机器学习课程编程作业(Exercise 2)及总结

    Exercise 1:Linear Regression---实现一个线性回归 关于如何实现一个线性回归,请参考:http://www.cnblogs.com/hapjin/p/6079012.htm ...

  7. Jquery 的遍历,祖先、后代、同胞以及其过滤

    什么是遍历? jQuery 遍历,意为“移动”,用于根据其相对于其他元素的关系来“查找”(或选取)HTML 元素.以某项选择开始,并沿着这个选择移动,直到抵达您期望的元素为止. 下图展示了一个家族树. ...

  8. linux tar命令简介

    一.使用介绍 1.名词区分 打包:将一大堆文件或目录变成一个总的文件[tar命令] 压缩:将一个大的文件通过一些压缩算法变成一个小文件[gzip,bzip2等] Linux中很多压缩程序只能针对一个文 ...

  9. [麦先生]SEO--相关优化【基础】

    收录的一个重要原则:离首页的远近.离首页太远,不容易被收录.内页必须距离首页3-4次点击之内. 原因:1.对于一个网站来说,搜索引擎经常来的地方是首页,因为很多外部链接链向的是首页如友情链接.做的外链 ...

  10. JustWeEngine - 轻量级游戏框架

    JustWeEngine - 轻量级游戏框架 An easy open source Android game engine. Github地址 引擎核心类流程图 使用方法 引入Engine作为Lib ...