当前位置: 首页 > news >正文

【图论】【数据结构】图的深度优先与广度优先遍历、最短路径

用栈实现图的深度优先遍历,队列实现广度优先遍历。

深度优先遍历

#!/usr/bin/python3
import random
import enum
import itertools
import mathCol = enum.Enum("Color", ("White", "Gray", "Black"))def DFS(G, s):visited = set()Q = []Q.append(s)visited.add(s)while Q:u = Q.pop()print(u)for i in G[u]:if i not in visited:Q.append(i)visited.add(i)def BFS(G, s):visited = set()Q = []Q.append(s)visited.add(s)while Q:u = Q.pop(0)print(u)for i in G[u]:if i not in visited:Q.append(i)visited.add(i)class Vertex:_cnt = 0# @staticmethoddef __init__(self, u, col, pi):self._cnt += 1self.u = uself.col = colself.pi = piself.d = math.infself.dt = 0self.ft = 0@propertydef Count(self):return self._cntdef __repr__(self):# return "Vertex(%s, col %s, perceding %s)" % (self.u, self.col, self.pi)return "%s" % self.u# A* keep with reference book
def ABFS(G, s):s.col = Col.Grays.d = 0s.pi = NoneQ = []Q.append(s)while Q:u = Q.pop(0)for x in G[u]:if x.col == Col.White:x.col = Col.Grayx.d = u.d + 1x.pi = uQ.append(x)u.col = Col.Blackdef AShortestPath(G, s, e, path=[]):if e == s:print(s)path.append(s)returnelif e.pi == None:print("No path from", s, "to", e)else:AShortestPath(G, s, e.pi, path)print(e)path.append(e)def FindPath(G, s, e, p):# [] just for enhancing list +p += [s]if s == e:return pfor n in G[s]:if n not in p:np = FindPath(G, n, e, p)if np:return npreturn Nonedef findAllPath(graph, start, end, path=[]):path = path + [start]if start == end:return [path]paths = []  # 存储所有路径for node in graph[start]:if node not in path:newpaths = findAllPath(graph, node, end, path)for newpath in newpaths:paths.append(newpath)return pathsdef isNotRepeat(all, a):for i in all:s = set(i)sa = set(a)if sa.issubset(s):return Falsereturn Truedef findMaxClique(graph):print("Start")clique_set = []# 遍历该团的顶点,for a in graph.keys():#  遍历顶点,对每个顶点查找其相邻顶点,构建初始团cli_can = [a, graph[a][random.randrange(0, len(graph[a]))]]if isNotRepeat(clique_set, cli_can):for i in cli_can:# 对其相邻neighbour顶点,若已经在团内的跳过,判断可否加入团,nb = graph[i]for j in nb:if j in cli_can:continueelse:is_memb = Truefor ii in cli_can:if j not in graph[ii]:is_memb = Falsebreakif is_memb:cli_can.append(j)clique_set.append(cli_can)n_max = 0mc = None# 比较各个团的大小。for c in clique_set:num = len(c)if num > n_max:n_max = nummc = creturn mcif __name__ == "__main__":G = []v0 = Vertex("s", Col.White, None)v01 = Vertex("r", Col.White, None)v02 = Vertex("w", Col.White, None)v0.next = v01v01.next = v02G.append(v0)v1 = Vertex("w", Col.White, None)v11 = Vertex("s", Col.White, None)v12 = Vertex("t", Col.White, None)v13 = Vertex("x", Col.White, None)v1.next = v11v11.next = v12v12.next = v13G.append(v1)print("Broad First Search")Ga = {# 0"r": ["s", "v"],# 1"s": ["r", "w"],# 2"t": ["w", "x", "u"],# 3"u": ["t", "x", "y"],# 4"v": ["r"],# 5"w": ["s", "t", "x"],# 6"x": ["w", "t", "u", "y"],# 7"y": ["x", "u"],}BFS(Ga, "s")DFS(Ga, "s")path = []print("FindPath", FindPath(Ga, "s", "y", []))graph = {"A": ["B", "C", "D"],"B": ["E"],"C": ["D", "F"],"D": ["B", "E", "G"],"E": [],"F": ["D", "G"],"G": ["E"],}ap = []findAllPath(graph, "A", "G", ap)alph = "rstuvwxy"lv = [Vertex(i, Col.White, Vertex(None, None, None)) for i in itertools.chain(alph)]m = dict(zip(alph, range(len(alph))))Gb = {}for (k, v) in Ga.items():key = lv[m[k]]Gb[key] = [lv[m[i]] for i in v]print(Gb)ABFS(Gb, lv[m["s"]])path = []AShortestPath(Ga, lv[m["s"]], lv[m["u"]], path)print(path)

递归方式实现DFS,

import enum
import mathCol = enum.Enum("Color", ("White", "Gray", "Black"))class Vertex:_cnt = 0# @staticmethoddef __init__(self, u, col, pi):self._cnt += 1self.u = uself.col = colself.pi = piself.d = math.infself.dt = 0self.ft = 0@propertydef Count(self):return self._cntdef __repr__(self):# return "Vertex(%s, col %s, perceding %s)" % (self.u, self.col, self.pi)return "%s" % self.uclass SolutionDFS:def __init__(self):self.time = 0def ADFS_VISIT(self, G, u):self.time += 1u.dt = self.timeu.col = Col.Grayfor v in G[u]:if v.col == Col.White:v.pi = uself.ADFS_VISIT(G, v)u.col = Col.Blackself.time += 1u.ft = self.timedef ADFS(self, G):for v in G.keys():v.col = Col.Whitev.pi = Noneself.time = 0for v in G.keys():if v.col == Col.White:self.ADFS_VISIT(G, v)
http://www.dtcms.com/a/404147.html

相关文章:

  • 制作网站作业wordpress设置关键字
  • 网站建设 seo模块泉州企业网站维护定制
  • 如何做音乐分享类网站个人网页制作模板田田田田田田田田
  • 网站建设需求说明书怎么写做婚礼效果图的网站有哪些
  • 温州免费建站私密浏览器视频
  • 速通ACM省铜第十四天 赋源码(Coloring Game)
  • 淮安做网站seo海南省建设注册执业资格中心网站
  • 阿里云 PAI 携手 NVIDIA 提供端到端物理 AI 解决方案
  • 如何用织梦程序制作多个页面网站承接电商网站建设
  • location配置 rewrite配置
  • 建设网站查证书哈尔滨网站建设教学
  • 弧光之源网站建设永久免费国外vps无需信用卡
  • 学校网站建河北省建设厅网站重新安装
  • 南京高端网站设计网站建设公司网站建设公司
  • 深圳seo网站oa系统app下载
  • 此网站不支持下载视频怎么办网站主题编辑工具WordPress
  • 网站的建设维护更换wordpress主题头部
  • 网页模板网站网站建设师特点
  • 网站建设的简洁性郑州市中标公示网
  • 技术速递|如何使用 Playwright MCP 和 GitHub Copilot 调试 Web 应用
  • 网站引用优酷广州做网站制作公司
  • EPGF架构:Python开发的长效稳定之道
  • 运营的网站wordpress导出文章word
  • 用dw做的个人网站外贸公司业务流程
  • 网站建设的基本流程包括文字转码unicode
  • 网站开发思路怎么写域名ip
  • 最新网站查询安康市建设规划局网站
  • 讲一讲什么是重要性采样
  • LLMs之Agent:agents-towards-production的简介、安装和使用方法、案例应用之详细攻略
  • 赤水市住房和城乡建设局网站西宁做网站君博优选