邻接矩阵
class Vertex:
def __init__(self, node):
self.id = node
# Mark all nodes unvisited
self.visited = False def addNeighbor(self, neighbor, G):
G.addEdge(self.id, neighbor) def getConnections(self, G):
return G.adjMatrix[self.id] def getVertexID(self):
return self.id def setVertexID(self, id):
self.id = id def setVisited(self):
self.visited = True def __str__(self):
return str(self.id) class Graph:
def __init__(self, numVertices=10, directed=False):
self.adjMatrix = [[None] * numVertices for _ in range(numVertices)]
self.numVertices = numVertices
self.vertices = []
self.directed = directed
for i in range(0, numVertices):
newVertex = Vertex(i)
self.vertices.append(newVertex) def addVertex(self, vtx, id): #增加点,这个function没有扩展功能
if 0 <= vtx < self.numVertices:
self.vertices[vtx].setVertexID(id) def getVertex(self, n):
for vertxin in range(0, self.numVertices):
if n == self.vertices[vertxin].getVertexID():
return vertxin
return None def addEdge(self, frm, to, cost=0): #返回全部连线/航线
#print("from",frm, self.getVertex(frm))
#print("to",to, self.getVertex(to))
if self.getVertex(frm) is not None and self.getVertex(to) is not None:
self.adjMatrix[self.getVertex(frm)][self.getVertex(to)] = cost
if not self.directed:
# For directed graph do not add this
self.adjMatrix[self.getVertex(to)][self.getVertex(frm)] = cost def getVertices(self):
vertices = []
for vertxin in range(0, self.numVertices):
vertices.append(self.vertices[vertxin].getVertexID())
return vertices def printMatrix(self):
for u in range(0, self.numVertices):
row = []
for v in range(0, self.numVertices):
row.append(str(self.adjMatrix[u][v]) if self.adjMatrix[u][v] is not None else '/')
print(row) def getEdges(self):
edges = []
for v in range(0, self.numVertices):
for u in range(0, self.numVertices):
if self.adjMatrix[u][v] is not None:
vid = self.vertices[v].getVertexID()
wid = self.vertices[u].getVertexID()
edges.append((vid, wid, self.adjMatrix[u][v]))
return edges def getNeighbors(self, n):
neighbors = []
for vertxin in range(0, self.numVertices):
if n == self.vertices[vertxin].getVertexID():
for neighbor in range(0, self.numVertices):
if (self.adjMatrix[vertxin][neighbor] is not None):
neighbors.append(self.vertices[neighbor].getVertexID())
return neighbors def isConnected(self, u, v):
uidx = self.getVertex(u)
vidx = self.getVertex(v)
return self.adjMatrix[uidx][vidx] is not None def get2Hops(self, u): #转一次机可以到达哪里
neighbors = self.getNeighbors(u)
print(neighbors)
hopset = set()
for v in neighbors:
hops = self.getNeighbors(v)
hopset |= set(hops)
return list(hopset)

邻接表
import sys
class Vertex:
def __init__(self, node):
self.id = node
self.adjacent = {}
#为所有节点设置距离无穷大
self.distance = sys.maxsize
# 标记未访问的所有节点
self.visited = False
# Predecessor
self.previous = None def addNeighbor(self, neighbor, weight=0):
self.adjacent[neighbor] = weight # returns a list
def getConnections(self): # neighbor keys
return self.adjacent.keys() def getVertexID(self):
return self.id def getWeight(self, neighbor):
return self.adjacent[neighbor] def setDistance(self, dist):
self.distance = dist def getDistance(self):
return self.distance def setPrevious(self, prev):
self.previous = prev def setVisited(self):
self.visited = True def __str__(self):
return str(self.id) + ' adjacent: ' + str([x.id for x in self.adjacent]) def __lt__(self, other):
return self.distance < other.distance and self.id < other.id class Graph:
def __init__(self, directed=False):
# key is string, vertex id
# value is Vertex
self.vertDictionary = {}
self.numVertices = 0
self.directed = directed def __iter__(self):
return iter(self.vertDictionary.values()) def isDirected(self):
return self.directed def vectexCount(self):
return self.numVertices def addVertex(self, node):
self.numVertices = self.numVertices + 1
newVertex = Vertex(node)
self.vertDictionary[node] = newVertex
return newVertex def getVertex(self, n):
if n in self.vertDictionary:
return self.vertDictionary[n]
else:
return None def addEdge(self, frm, to, cost=0):
if frm not in self.vertDictionary:
self.addVertex(frm)
if to not in self.vertDictionary:
self.addVertex(to) self.vertDictionary[frm].addNeighbor(self.vertDictionary[to], cost)
if not self.directed:
# For directed graph do not add this
self.vertDictionary[to].addNeighbor(self.vertDictionary[frm], cost) def getVertices(self):
return self.vertDictionary.keys() def setPrevious(self, current):
self.previous = current def getPrevious(self, current):
return self.previous def getEdges(self):
edges = []
for key, currentVert in self.vertDictionary.items():
for nbr in currentVert.getConnections():
currentVertID = currentVert.getVertexID()
nbrID = nbr.getVertexID()
edges.append((currentVertID, nbrID, currentVert.getWeight(nbr))) # tuple
return edges def getNeighbors(self, v):
vertex = self.vertDictionary[v]
return vertex.getConnections()

引入的这两段代码的原文链接:
https://www.cnblogs.com/kumata/p/9246502.html

Python实现数据结构 图的更多相关文章

  1. python 与数据结构

    在上面的文章中,我写了python中的一些特性,主要是简单为主,主要是因为一些其他复杂的东西可以通过简单的知识演变而来,比如装饰器还可以带参数,可以使用装饰类,在类中不同的方法中调用,不想写的太复杂, ...

  2. [0x00 用Python讲解数据结构与算法] 概览

    自从工作后就没什么时间更新博客了,最近抽空学了点Python,觉得Python真的是很强大呀.想来在大学中没有学好数据结构和算法,自己的意志力一直不够坚定,这次想好好看一本书,认真把基本的数据结构和算 ...

  3. (python数据分析)第03章 Python的数据结构、函数和文件

    本章讨论Python的内置功能,这些功能本书会用到很多.虽然扩展库,比如pandas和Numpy,使处理大数据集很方便,但它们是和Python的内置数据处理工具一同使用的. 我们会从Python最基础 ...

  4. Python入门神图

    国外某小哥制作的Python入门神图

  5. 【ZZ】Python入门神图

    http://mp.weixin.qq.com/s?__biz=MzA3OTIxNTA0MA==&mid=401383338&idx=1&sn=73009cce06d58656 ...

  6. Python -- 堆数据结构 heapq - I love this game! - 博客频道 - CSDN.NET

    Python -- 堆数据结构 heapq - I love this game! - 博客频道 - CSDN.NET Python -- 堆数据结构 heapq 分类: Python 2012-09 ...

  7. python实现数据结构单链表

    #python实现数据结构单链表 # -*- coding: utf-8 -*- class Node(object): """节点""" ...

  8. 《用Python解决数据结构与算法问题》在线阅读

    源于经典 数据结构作为计算机从业人员的必备基础,Java, c 之类的语言有很多这方面的书籍,Python 相对较少, 其中比较著名的一本 problem-solving-with-algorithm ...

  9. 数据结构--图 的JAVA实现(上)

    1,摘要: 本系列文章主要学习如何使用JAVA语言以邻接表的方式实现了数据结构---图(Graph),这是第一篇文章,学习如何用JAVA来表示图的顶点.从数据的表示方法来说,有二种表示图的方式:一种是 ...

随机推荐

  1. Linux中的block容量

    block容量的大小直接关系到文件系统存储使用是否合理的问题: 因为每个block只能供一个文件使用,所以如果Linux系统的block容量太大,但系统经常存储的都是小文件那么会很浪费系统磁盘: 但如 ...

  2. Centos 6.4 安装Mplayer 播放器

    1.Download the rpmforge-release package. URL1:x86_64.rmp URL2:tar.gz    推荐!!! 2.Install DAG's GPG ke ...

  3. Java程序员阅读源码的小技巧,原来大牛都是这样读的,赶紧看看!

    今天介跟大家分享一下我平时阅读源码的几个小技巧,对于阅读java中间件如Spring.Dubbo等框架源码的同学有一定帮助. 本文基于Eclipse IDE,我们每天都使用的IDE其实提供了很多强大的 ...

  4. 哎,老了之display-box

    哎,不想吐槽自己了,表示已远远落后,从今天起开始恶补吧,来一个实例 <html> <head> <meta name="generator" cont ...

  5. TCP Wrappers(简单防火墙)---限制IP登录ssh

    1.TCP Wrappers 简介 TCP_ Wrappers是- 一个工作在第四层(传输层)的的安全工具,对有状态连接(TCP)的特定服务进行安全检测并实现访问控制,界定方式是凡是调用libwrap ...

  6. Kail系统更新指令

    0x00源更新 国内更新源 leafpad /etc/apt/sources.list 然后复制粘贴下面的源 #kali官方源 deb http://http.kali.org/kali kali-r ...

  7. 一个howdoo的预兆

    原文链接:https://medium.com/howdoo/its-an-omen-for-howdoo-b33b831ed936 它是一个预兆.它是刻在墙上的.它不会消失 随着越来越多的人对Fac ...

  8. 蕴含式(包含EXISTS语句的分析)

    *{ font-family: STFangSong; outline: none; } 蕴含式 一.蕴含式基础 (Ⅰ)什么是"蕴含式" 设p.q为两个命题.复合命题"如 ...

  9. MYSQL 之 JDBC(五): 增删改查(三)PreparedStatement

    是Statement的子接口,可以传入带占位符的sql语句,并且提供了补充占位符变量的方法. 使用Statement需要进行拼写SQL语句,很辛苦,很容易出错. 引号的问题处理很复杂,不利于维护. 可 ...

  10. java 数据结构(七):Collection接口

    1.单列集合框架结构|----Collection接口:单列集合,用来存储一个一个的对象* |----List接口:存储序的.可重复的数据. -->“动态”数组* |----ArrayList. ...