图: 广度深度优先遍历(邻接表)
来源:互联网 发布:淘宝可以海外淘宝网 编辑:程序博客网 时间:2024/05/18 03:40
//图的广度深度优先遍历
//说明: 采用邻接表存储
//顶点表由结构体构成,结构体包括顶点,visit(该节点是否被访问过),邻接点指针
//09.8.9
//09.8.10修改(增加DFS)
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
//邻接点结构体
struct Node
{
int vertex;
Node *next;
Node ():next(NULL){}
};
//节点表结构体
struct Ver_tab
{
int vertex;
int visit ;
Node *next;
Ver_tab ():visit(0),next(NULL) {}
};
//建立邻接表
void CreateTable (vector<Ver_tab> &ver_table)
{
//分两步
//第一,建立节点表
int ver_num;
cout<<"input the number of the vertexes : "; cin>>ver_num;
ver_table[0].vertex = ver_num; //节点个数放在表头vertex位置
for (int i = 1; i <= ver_num; i++)
ver_table[i].vertex = i;
//第二,增加邻接节点
int edge_num; //边的条数
cout<<"input the number of the edges : "; cin>>edge_num;
ver_table[0].visit = edge_num; //边的条数放在表头visit位置
int a1 , a2;
for (i = 0; i < edge_num; i++)
{
cin>>a1>>a2;
//点a2后面增加一个邻接点a1
Node * node1 = new Node;
node1->vertex = a1;
node1->next = ver_table[a2].next;
ver_table[a2].next = node1;
//点a1后面增加二个邻接点a2
Node * node2 = new Node;
node2->vertex = a2;
node2->next = ver_table[a1].next;
ver_table[a1].next = node2;
}
}
//广度优先遍历
void BFS (vector<Ver_tab> ver_table)
{
cout<<"input the position you want to begin : ";
int begin; cin>>begin;
queue<int> qu;
qu.push (begin);
cout<<qu.front()<<ends; ver_table[begin].visit = 1;
while (!qu.empty())
{
int tmp = qu.front();
//BFS核心代码
for (Node *p = ver_table[tmp].next; p != NULL ; p = p->next)
{
int vertex = p->vertex;
if (ver_table[vertex].visit == 0)
{
cout<<vertex<<ends; ver_table[vertex].visit = 1;
qu.push (vertex);
}
}
qu.pop();
}
cout<<endl;
}
//深度遍历递归函数
void Dfs (vector<Ver_tab> &ver_table , int vertex)
{
//DFS核心代码
cout<<vertex<<ends; ver_table[vertex].visit = 1;
for (Node *p = ver_table[vertex].next ; p != NULL; p = p->next)
if (ver_table[p->vertex].visit == 0)
Dfs (ver_table , p->vertex);
}
//深度优先遍历(递归实现)
void DFS (vector<Ver_tab> ver_table)
{
cout<<"DFS: input the position you want to begin : ";
int begin; cin>>begin;
Dfs (ver_table , begin);
cout<<endl;
}
//主函数
int main ()
{
vector<Ver_tab> ver_table(1000);
CreateTable (ver_table);
BFS (ver_table);
DFS (ver_table);
return 0;
}
- 图: 广度深度优先遍历(邻接表)
- 图邻接表存储 深度优先和广度优先遍历
- 邻接表-图的遍历-广度和深度优先遍历
- 邻接表存储图,深度和广度优先遍历
- 图(邻接表)的深度、广度优先遍历
- 邻接图的广度优先遍历和深度优先遍历
- 邻接表的深度优先遍历以及广度优先遍历
- 图算法:1、邻接表实现图的深度优先遍历,广度优先遍历
- 图的邻接表存储 深度优先遍历 广度优先遍历 C语言实现
- 图的邻接表存储 深度优先遍历 广度优先遍历 C语言实现
- 无向图的深度优先遍历和广度优先遍历(邻接链表)
- 图的邻接表(广度优先遍历,深度优先遍历,最小生成树(Kruskal算法))
- 邻接表实现--图的深度优先遍历DFS和广度优先遍历BFS
- 邻接表深度优先遍历和广度遍历
- 图的深度优先和广度优先遍历算法(用邻接表作为存储结构)
- 建立图的邻接表储存并实现深度优先和广度优先遍历
- 邻接表存储图的深度优先、广度优先遍历非递归算法
- 基于邻接表储存的图的深度优先和广度优先遍历
- 简单模式
- hdu acm 2106 decimal system
- C++ 虚函数表解析
- 使用SqlDataAdapter对象填充数据集
- 如何使用image映像文件
- 图: 广度深度优先遍历(邻接表)
- Dynamic Programing
- Hash Table used for net_device chain
- Linux kernel Studying constantly
- pku 2531 Network Saboteur(不会搜索,用的枚举)
- 61条面向对象的设计原则
- 去掉小数点后面的0
- 数据库中主键和外键的设计原则
- TCP原理