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

图的深度优先遍历

way:栈,map(或set,只是我想用map)记录是否访问过,放入时记录为已访问,打印,邻接的没访问过先入cur,再入邻接的节点,放入一个邻接的节点后及时break去下一个深度节点。(为什么要放入cur,因为需要遍历到全部节点,而不只是一条)

#include<iostream>
#include<vector>
#include<map>
#include<set>
#include<stack>
using namespace std;class Node;//边结构的描述
class Edge
{
public://边的起始节点Node *from;//边的终点节点Node *to;//边的权重int weight;
public:Edge(Node *from, Node *to, int weight){this->from = from;this->to = to;this->weight = weight;}
};//点结构的描述
class Node
{
public://编号值int value;//入度int in;//出度int out;//邻接的点vector<Node*> nexts;//邻接的边vector<Edge*> edges;
public:Node(){}Node(int value){this->value = value;in = 0;out = 0;}
};//图结构的描述
class Graph
{
public:map<int, Node*> nodes;set<Edge*> edges;Graph(){}
};//利用边结构描述的图来构建图结构
//[0,7,5]   [from,to,weight]
//[0,1,3]   [from,to,weight]
Graph* createGraph(vector<vector<int>> matrix)
{Graph *graph = new Graph();int m = matrix.size();for(int i=0; i<m; i++){int from = matrix[i][0];int to = matrix[i][1];int weight = matrix[i][2];//将起点结构放到图里面if(!graph->nodes.count(from)){Node *fromNode =new Node(from);graph->nodes[from] = fromNode;}//将终点结构放到图里面if(!graph->nodes.count(to)){Node *toNode=new Node(to);graph->nodes[to] = toNode;}//将起点和终点的边结构也放到图里面(点可能已经存在过,边一定是新的)Node *fromNode = graph->nodes[from];Node *toNode = graph->nodes[to];Edge *newEdge = new Edge(fromNode, toNode, weight);fromNode->nexts.push_back(toNode);fromNode->edges.push_back(newEdge);fromNode->out++;toNode->in++;graph->edges.insert(newEdge);}return graph;
}void dfs(Node *start)
{map<Node*,bool>vis;stack<Node*> st;st.push(start);vis[start]=true;cout<<start->value<<" ";while(!st.empty()){Node *cur = st.top();st.pop();for(auto next: cur->nexts){if(vis.count(next)==0){st.push(cur);st.push(next);vis[next]=true;cout<<next->value<<" ";break;}}}cout<<endl;
}
http://www.lryc.cn/news/349302.html

相关文章:

  • 13 华三三层链路聚和
  • C# 下载安装,使用OfficeOpenXml
  • Spring整体流程源码分析
  • 使用XxlCrawler抓取全球航空公司ICAO三字码
  • Java String转JSONObject时保持字段顺序不变
  • Optional用法
  • 【观成科技】加密C2框架Xiebro流量分析
  • 【八大排序算法】插入排序、希尔排序、选择排序、堆排序、冒泡排序、快速排序、归并排序、计数排序
  • Flutter 中的 CupertinoActionSheet 小部件:全面指南
  • IDEA 好用的插件
  • leetcode——链表的中间节点
  • 稳定网络的诀窍:静态住宅代理解决方案
  • VACode 创建Vue项目完整过程
  • 【C++】详解C++的模板
  • 1146 -Table ‘performance schema.session variables‘ doesn‘t exist的错误解决
  • 练习题(2024/5/13)
  • LeetCode—设计循环队列(两种方法)
  • python “名称空间和作用域” 以及 “模块的导入和使用”
  • Pycharm导入自定义模块报红
  • LLMs之KG-RAG:KG-RAG(基于知识图谱的RAG系统)的简介(可以解决多跳问题/同时支持结构化和非结构化数据查询)、经验技巧、案例应用之详细攻略
  • 综合模型及应用(图论学习总结部分内容)
  • 2025考研专业课、英语、数学、政治视频大全,整理全了!
  • 设计模式之策略模式(一)
  • 常见网络攻击及解决方案
  • 【挑战30天首通《谷粒商城》】-【第一天】【10 番外篇】 解决docker 仓库无法访问 + MobaXterm连接VirtualBox虚拟机
  • 【C++】每日一题 17 电话号码的字母组合
  • vue预览PDF文件的几种方法
  • 深度学习入门到放弃系列 - 阿里云人工智能平台PAI部署开源大模型chatglm3
  • GPT-4o,AI实时视频通话丝滑如人类,Plus功能免费可用
  • 【优选算法】——Leetcode——202—— 快乐数