
大二数据结构(图的深度遍历的 非递归算法)
发布日期:2021-05-07 23:24:20
浏览次数:13
分类:原创文章
本文共 1869 字,大约阅读时间需要 6 分钟。
#include <stdio.h>#include <stdlib.h>#define maxSize 20 typedef struct ArcNode{ int adjvex; struct ArcNode *nextarc;}ArcNode; typedef struct{ char data; struct ArcNode *firstarc;}VNode; typedef struct{ VNode adjlist[maxSize]; int n, e;}AGraph; void createGraph(AGraph *G){ int i, tail, head, edges, vertex; ArcNode *tmp, *p; printf("请输入图的顶点数:"); scanf("%d", &vertex); printf("请输入图的边数:"); scanf("%d", &edges); G->n = vertex; G->e = edges; for (i = 1; i <= edges; ++i) { printf("请输入第%d条边的弧尾与弧头\n", i); printf("弧尾: "); scanf("%d", &tail); printf("弧头: "); scanf("%d", &head); p = (ArcNode *)malloc(sizeof(ArcNode)); p->adjvex = head; p->nextarc = NULL; //建立邻接表 tmp = G->adjlist[tail].firstarc; if(tmp == NULL) G->adjlist[tail].firstarc = p; else{ while (tmp->nextarc != NULL) tmp = tmp->nextarc; tmp->nextarc = p; } } printf("图建立完毕\n");} void DFSNonRecursion(AGraph *G, int v){ printf("图DFS开始\n"); int stack[maxSize]; int top = -1; int visit[maxSize]; int i, j, k; ArcNode *p; for (i = 0; i < maxSize; ++i) visit[i] = 0; printf("%d ", v); visit[v] = 1; stack[++top] = v; while (top != -1) { j = stack[top]; p = G->adjlist[j].firstarc; while (p != NULL) { while (p != NULL && visit[p->adjvex] == 1) p = p->nextarc; if(p == NULL) break; k = p->adjvex; stack[++top] = k; visit[k] = 1; printf("%d ", k); p = G->adjlist[k].firstarc; } --top; } printf("\n图DFS完毕\n");} int main(){ AGraph G; createGraph(&G); DFSNonRecursion(&G, 0); return 0;}
发表评论
最新留言
留言是一种美德,欢迎回访!
[***.207.175.100]2025年04月07日 21时52分03秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
分组背包问题
2019-03-05
子集(LeetCode 78)
2019-03-05
旋转数组的最小值
2019-03-05
1004 Counting Leaves (30分)
2019-03-05
1093 Count PAT‘s (25分) 含DP做法
2019-03-05
一篇解决JMM与volatile详解(二)
2019-03-05
数据结构之数组与经典面试题(二)
2019-03-05
无锁并发框架-Disruptor的使用(二)
2019-03-05
Android wm命令
2019-03-05
boot.img 解包与打包
2019-03-05
Android4.4 平板背光设置
2019-03-05
递归复习--二叉搜索树
2019-03-05
jvm-02
2019-03-05
spring boot@Value和bean执行顺序问题
2019-03-05
从浏览器输入网址到服务器返回经历的过程
2019-03-05
解决Genymotion无法拖拽的问题
2019-03-05
中国石油大学《计算机文化基础》在线考试(客观题)
2019-03-05
中国石油大学《 管理心理学(行政管理专业禁选)》在线考试
2019-03-05
机器学习(numpy/matplotlib/scipy)学习笔记
2019-03-05