DFS BFS遍历图 邻接表实现
2012-12-14 12:25
483 查看
#include<iostream> #include<queue> #include<stack> #include<map> #include<cstring> using namespace std; #define MAX 1000 map<char,bool> maps; map<char,bool>::iterator it; struct edge { char c; edge *next; edge():next(NULL){} }; struct vertex { char c; edge *next; vertex():next(NULL){} }; vertex ver[MAX]; void DFS(int num) { stack<vertex> sta; vertex temp; edge *te; sta.push(ver[0]); while(!sta.empty()) { temp=sta.top(); if(!maps[temp.c]) { cout<<temp.c<< ' '; maps[temp.c]=true; } sta.pop(); te=temp.next; while(te) { if(!maps[te->c]) sta.push(ver[te->c-'A']); te=te->next; } } cout<<endl; } void BFS(int num) { queue<vertex> que; vertex temp; edge *te; que.push(ver[0]); while(!que.empty()) { temp=que.front(); if(!maps[temp.c]) { cout<<temp.c<< ' '; maps[temp.c]=true; } que.pop(); te=temp.next; while(te) { if(!maps[te->c]) que.push(ver[te->c-'A']); te=te->next; } } cout<<endl; } int main() { int num,ednum,state; char c,d; edge *p,*t; cout<<"输入顶点数,边数"<<endl; cin>>num>>ednum; cout<<"输入何种图 1:有向图 0:无向图"<<endl; cin>>state; cout<<"输入"<<num<<"个顶点,必须是正序大写字母如:A B C D E F G H"<<endl; for(int i=0;i<num;i++) { cin>>ver[i].c; maps[ver[i].c]=false; } cout<<"输入"<<ednum<<"条边,如:A B"<<endl; for(int i=0;i<ednum;i++) { cin>>c>>d; p=new edge; p->c=d; if(ver[c-'A'].next==NULL) ver[c-'A'].next=p; else { t=ver[c-'A'].next; while(t->next) t=t->next; t->next=p; } if(!state) { p=new edge; p->c=c; if(ver[d-'A'].next==NULL) ver[d-'A'].next=p; else { t=ver[d-'A'].next; while(t->next) t=t->next; t->next=p; } } } cout<<"输入需要操作的序号!"<<endl <<"1.广度搜索 2.深度搜索"<<endl; while(cin>>c) { switch(c) { case '1': BFS(num); for(it=maps.begin();it!=maps.end();++it) (*it).second=false; break; case '2': DFS(num); for(it=maps.begin();it!=maps.end();++it) (*it).second=false; break; default: break; } cout<<"输入需要操作的序号!(EOF结束(Ctrl+Z))"<<endl <<"1.广度搜索 2.深度搜索"<<endl; } return 0; }
相关文章推荐
- 邻接表实现--图的深度优先遍历DFS和广度优先遍历BFS
- 用邻接表存储有向图并实现DFS(递归+非递归)BFS(非递归)两种遍历
- 邻接表深度和广度遍历DFS_BFS.c
- 数据结构之——用C++实现邻接表的DFS与BFS
- 图的邻接表 表示 DFS 和BFS C++实现
- 图(邻接表)的遍历——DFS(深度优先搜索)和BFS(广度优先搜索)和连通图
- 关于邻接表实现适用两种深搜(DFS)和广搜(BFS)的代码
- 邻接表深度优先和广度优先遍历(DFS和BFS)
- java实现邻接表图、DFS、BFS
- 邻接矩阵实现--图的深度优先遍历DFS和广度优先遍历BFS
- 第七章 图(邻接矩阵和邻接表建立图并实现DFS、BFS)
- 邻接矩阵实现图的存储,DFS,BFS遍历
- 图的邻接表存储及DFS,BFS遍历
- 用邻接表存储有向图实现的dfs和bfs
- 深度遍历(DFS)与广度遍历(BFS) (C语言实现)
- 第六章:图。(邻接表实现图的存储及dfs、bfs)
- 数据结构 《2》----基于邻接表表示的图的实现 DFS(递归和非递归), BFS
- 基于邻接矩阵和邻接表的两种方法实现无向图的BFS和DFS
- 数据结构 学习笔记(七):图(上):图的表示方法(邻接表,邻接矩阵),遍历(DFS,BFS)
- java版 图的邻接表、邻接矩阵、BFS、DFS 实现