邻接矩阵
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. JDK8 日期格式化

    SpringBoot 是为了简化 Spring 应用的创建.运行.调试.部署等一系列问题而诞生的产物,自动装配的特性让我们可以更好的关注业务本身而不是外部的XML配置,我们只需遵循规范,引入相关的依赖 ...

  2. 分析并封装排序算法(js,java)

    前言 本次来分享一下排序的api底层的逻辑,这次用js模拟,java的逻辑也是差不多. 先看封装好的api例子: js的sort排序 java的compareTo排序 自己模拟的代码(JS) func ...

  3. let import export React入门实例教程 connect provider combineReducers 箭头函数 30分钟掌握ES6/ES2015核心内容 Rest babel

    let与var的区别 http://www.cnblogs.com/snandy/archive/2015/05/10/4485832.html es6 导入导出 http://www.csdn.ne ...

  4. PTP时钟和NTP时钟同步有什么区别

    PTP时钟 理论上任何PTP时钟都能实现主时钟和从时钟的功能,但一个PTP通信子网内只能有一个主时钟.整个系统中的最优时钟为最高级时钟GMC(Grandmaster Clock),有着最好的稳定性.精 ...

  5. 单调栈之WYT的刷子

    好久没更题解了(改题困难的我) 题目描述 WYT有一把巨大的刷子,刷子的宽度为M米,现在WYT要使用这把大刷子去粉刷有N列的栅栏(每列宽度都为1米:每列的高度单位也为米,由输入数据给出). 使用刷子的 ...

  6. How many ways??,题解

    题目: 题意: 找过k条边的路径个数. 分析: 首先注意一下题意,同一个点过两次算两次,做过类似的,过k条边的最短路,只要搞一个矩阵,然后快速幂就好了,这个也一样,维护信息变一下,然后就好了. 如果k ...

  7. PE文件格式详解(二)

    0x00 前言 上一篇讲到了PE文件头的中IMAGE_FILE_HEADER结构的第二个结构,今天从IMAGE_FILE_HEADER中第三个结构sizeOfOptionalHeader讲起.这个字段 ...

  8. 如何实现 token 加密

    jwt举例 需要一个secret(随机数) 后端利用secret和加密算法(如:HMAC-SHA256)对payload(如账号密码)生成一个字符串(token),返回前端 前端每次request在h ...

  9. web notification api

    Web Notifications API 使页面可以发出通知,通知将被显示在页面之外的系统层面上(通常使用操作系统的标准通知机制,但是在不同的平台和浏览器上的表现会有差异) 要显示一条通知,你需要先 ...

  10. 机器学习实战基础(十二):sklearn中的数据预处理和特征工程(五) 数据预处理 Preprocessing & Impute 之 处理分类特征:处理连续性特征 二值化与分段

    处理连续性特征 二值化与分段 sklearn.preprocessing.Binarizer根据阈值将数据二值化(将特征值设置为0或1),用于处理连续型变量.大于阈值的值映射为1,而小于或等于阈值的值 ...