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. 从技术经理的角度算一算,如何可以多快好省的做个app

    [导读]前端时间,一篇“从产品经理的角度算一算,做个app需要多少钱”的文章在网上疯传,可见大家对互联网创业的热情!这次,从一名技术经理的角度再给大家分析一下,如何使用跨平台开发技术为你节省上百万的开 ...

  2. 漏洞科普:对于XSS和CSRF你究竟了解多少

    转自:http://www.freebuf.com/articles/web/39234.html 随着Web2.0.社交网络.微博等等一系列新型的互联网产品的诞生,基于Web环境的互联网应用越来越广 ...

  3. Keepalived+MySQL双主架构

    l  架构准备 Node1 192.168.15.3 Node2 192.168.15.4 VIP 192.168.15.254 l  软件 MySQL 5.6 Keepalive yum insta ...

  4. who

    查看当前系统中当前登录的帐户 $who jiang :0 2016-10-13 08:55 (:0) jiang pts/4 2016-10-13 09:03 (:0) jiang pts/1 201 ...

  5. linux下使用Apache+php实现留言板功能的网站

    一.首先我们的linux服务器上要安装Apache和php 请参考:http://www.cnblogs.com/dagege/p/5949620.html 二.关闭防火墙服务,关闭selinux 请 ...

  6. 【redis使用全解析】常见运维操作

    作者:gnuhpc 出处:http://www.cnblogs.com/gnuhpc/ 1.1 启动 1.1.1 启动redis $ redis-server redis.conf 常见选项: ./r ...

  7. 我懒蛋又回来了!-PDO

    hi 好几天了吧,脚伤都有一周了的.玩乐的这么久才发觉,对于年轻人,或者更具体的,对我而言,受伤最难受的不是受伤瞬间的身痛,不是随之而来的心理负担,不是独自一人远在他乡的孤独无助之感:最伤的是斗志,是 ...

  8. 【原】js实现复制到剪贴板功能,兼容所有浏览器

    两天前听了一个H5的分享,会议上有一句话,非常有感触:不是你不能,而是你对自己的要求太低.很简单的一句话,相信很多事情不是大家做不到,真的是对自己的要求太低,如果对自己要求多一点,那么你取得的进步可能 ...

  9. Jetty使用攻略

    jetty作为一款小型的web容器用处很大,因为其小巧强大,经常作为嵌入式的组件处理http交互. Jetty 作为一个独立的 Servlet 引擎可以独立提供 Web 服务,但是它也可以与其他 We ...

  10. django csrf 处理简介

    CSRF 是什么 CSRF 即跨站请求伪造,在用户不知情的情况下向有漏洞的网站发送请求.例如有正常网站A,恶意网站B, 用户若对A B 两个网站都有访问,B 可能伪造请求到 A,比如提交表单.至于具体 ...