邻接表存储实现图的深度优先遍历
作者:@kuaiquxie
作者的github:https://github.com/bitebita
本文为作者原创,如需转载,请注明出处:https://www.cnblogs.com/dzwj/p/15609458.html
邻接表存储实现图的深度优先遍历
编写程序,实现由邻接表存储实现图的深度优先搜索遍历的功能。顶点为字符型。
输入格式:
第一行输入顶点个数及边的个数,第二行依次输入各顶点,第三行开始依次输入边的两个顶点,用空格分开。最后输入深度优先遍历的起始点。
输出格式:
输出深度优先遍历结果,空格分开,若起始点不合理,则输出error。
输入样例:
在这里给出一组输入。例如:
8 9
0 1 2 3 4 5 6 7
0 1
0 2
1 3
1 4
2 5
2 6
3 7
4 7
5 6
0
输出样例:
在这里给出相应的输出。例如:
0 2 6 5 1 4 7 3
#include<iostream> #include<queue> using namespace std; struct ArcNode { int adjvex; //该弧所指向的顶点的位置 ArcNode * next; //指向下一条弧的指针 //int weight;边上是否有权 }; typedef struct VNode { int vertex; //顶点信息 ArcNode * firstarc; //指向第一条依附该顶点的弧的指针 }AdjList[20]; struct ALGraph { AdjList adjList; int vexNum; //图的顶点数 int arcNum; //图的弧数 }; bool visited[20];//设置标志数组 void CreateGraph(ALGraph & graph); void DFSTraverse(ALGraph & graph); int temp_2=1; int main() { int temp_1; ALGraph graph; CreateGraph(graph); cin>>temp_1; //cout<<temp_1; for(int i=0;i<graph.vexNum;i++) { if(temp_1==graph.adjList[i].vertex) { temp_2=0; } } if(temp_2==0) { DFSTraverse(graph); } if(temp_2==1){ cout<<"error"; } return 0; } void CreateGraph(ALGraph & graph) { cin >> graph.vexNum; cin >> graph.arcNum; for (int i = 0; i < graph.vexNum; i++) { cin >> graph.adjList[i].vertex; graph.adjList[i].firstarc = nullptr; } int h1, h2; ArcNode * temp; for (int i = 0; i < graph.arcNum; i++) { cin >> h1 >> h2; temp = new ArcNode; temp->adjvex = h2; temp->next = graph.adjList[h1].firstarc; graph.adjList[h1].firstarc = temp; temp = new ArcNode; temp->adjvex = h1; temp->next = graph.adjList[h2].firstarc; graph.adjList[h2].firstarc = temp; } } void DFS(ALGraph & graph, int v) { visited[v] = true; cout << graph.adjList[v].vertex << " "; ArcNode * p = graph.adjList[v].firstarc; while (p) { if (!visited[p->adjvex]) DFS(graph, p->adjvex); p = p->next; } } void DFSTraverse(ALGraph & graph) { for (int i = 0; i < graph.vexNum; i++)//初始化访问标志数组 visited[i] = false; for (int i = 0; i < graph.vexNum; i++) { if (!visited[i])//如果没有访问 DFS(graph, i); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」