数据结构 — 图之邻接表存储创建和深度优先遍历
2015-11-20 16:14
531 查看
【描述】: 该graph采用邻接表存储,首先创建图,然后对其进行深度优先遍历。
【输入】:
8
1 2 -1
0 3 4 -1
0 5 6 -1
1 7 -1
1 7 -1
2 7 -1
2 7 -1
3 4 5 6 -1
【输出】:
0 1 3 7 4 5 2 6
【输入】:
8
1 2 -1
0 3 4 -1
0 5 6 -1
1 7 -1
1 7 -1
2 7 -1
2 7 -1
3 4 5 6 -1
【输出】:
0 1 3 7 4 5 2 6
/* * 无向图的邻接表创建 8 1 2 -1 0 3 4 -1 0 5 6 -1 1 7 -1 1 7 -1 2 7 -1 2 7 -1 3 4 5 6 -1 */ #include<iostream> #include<memory.h> using namespace std; #define MAX_VERTICES 50 /* 顶点最大数 */ #define ElementType int /* 元素的数据类型 */ bool visited[MAX_VERTICES]; /* 记录顶点是否被访问 */ typedef struct node { /* 表节点结构体 */ ElementType vertex; struct node *next; }NodeType,*NodePointer; NodePointer graph[MAX_VERTICES]; /* 头节点数组 */ int vertices; /* 顶点数量 */ void CreateGraph(){ ElementType ch; NodePointer pnew,qnode; pnew = qnode = NULL; for(int i = 0; i < vertices; i++){ cin>>ch; if(ch == -1) continue; /*当ch 为-1是结束该vertex的创建*/ //链表的头节点 pnew = new NodeType; pnew->vertex = ch; pnew->next = NULL; //将头节点存入 头节点数组 graph[i] = pnew; //尾插法创建链表 cin>>ch; while(ch != -1){ //申请内存、处理数据域、处理指针域 qnode = new NodeType; qnode->vertex = ch; qnode->next =NULL; //插入 pnew->next = qnode; //更新尾指针 pnew = qnode; cin>>ch; } } } void dfs(int v){ NodePointer np; //访问该vertex visited[v] = true; cout<<v<<" "; /* * 图深度优先遍历 * 1、访问该节点并且记录 * 2、当该节点的next节点没被visited,dfs(next节点) * 3、当该节点的next节点都被visited,结束for,退到上一个visited的节点执行2步骤 * 4、都被访问了,函数自然结束 */ for(np = graph[v]; np!=NULL; np = np->next){ if(!visited[np->vertex]) dfs(np->vertex); } } int main(){ memset(visited,false,sizeof(visited)); cout<<"输入顶点数"<<endl; cin>>vertices; CreateGraph(); cout<<"深度优先遍历"<<endl; dfs(0); return 0; }
相关文章推荐
- 封装TableView有可能用到的数据结构和UITableViewCell的一个继承类
- 最小生成树——Prim(普利姆)算法
- 找到一个数的所有字典序即字符串的全排列
- 最小生成树基础
- 二叉排序树和堆的区别
- 第十周--数据结构--用二叉树遍历思想解决问题
- 数据结构之二叉树递归操作
- leetcode之Basic Calculator II
- 数据结构之哈希表
- 数据结构(Java)——查找和排序(4)
- 【数据结构与算法分析】2.4 求最大子序列和
- 二叉树及其应用-二叉树的遍历及哈夫曼树-数据结构上机实验
- 第十周--数据结构--二叉树遍历的递归算法
- 数据结构(Java)——查找和排序(3)
- 数据结构例程——平衡二叉树
- 数据结构例程——二叉排序树
- 数据结构例程——分块查找
- 数据结构与基本运算
- 数据结构例程——线性表的折半查找
- 数据结构例程——线性表的顺序查找