图的深度优先遍历的实现C/C++ DFS
作者:网络转载 发布时间:[ 2015/2/27 11:46:38 ] 推荐标签:C++ 遍历
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
#define MAX 100
#define LENGTH(a) (sizeof(a) / sizeof(a[0]))
int visited[MAX];
typedef struct _graph{
char vexs[MAX];
int vexnum;
int edgnum;
int matrix[MAX][MAX];
}Graph,*PGgraph;
static int get_position(Graph g, char ch){
for(int i = 0;i<g.vexnum;i++){
if(ch == g.vexs[i])
return i;
}
return -1;
}
static char read_char(){
char ch;
while(!((((ch)>='a') && ((ch)<='z')) || (((ch)>='A') && ((ch)<='Z'))))
ch = getchar();
return ch;
}
Graph creat_graph(){
char c1,c2;
int v,e;
int p1,p2;
Graph pG;
cout<<"input number of vex > ";
cin>>v;
cout<<"input number of edge > ";
cin>>e;
//memset(pG,0,sizeof(Graph));
pG.vexnum = v;
pG.edgnum = e;
//Initialize vexs
for(int i=0; i<pG.vexnum;i++){
//pG.vexs[i] = read_char();
cin>>pG.vexs[i] ;
}
//Initialize edges
for(int i = 0;i < pG.edgnum; i++){
//c1 = read_char();
//c2 = read_char();
cin>>c1>>c2;
cout<<c1<<c2<<endl;
p1 = get_position(pG, c1);
p2 = get_position(pG, c2);
pG.matrix[p1][p2] = 1;
pG.matrix[p2][p1] = 1;
}
return pG;
}
static int next_vertex(Graph g, int v,int w){
if(v<0 || v>g.vexnum-1|| w<0 || w>(g.vexnum-1)) return -1;
for(int i=w+1; i < g.vexnum; i++){
if(g.matrix[v][i] == 1) return i;
}
return -1;
}
static int first_vertex(Graph g, int v){
if(v<0 || v>g.vexnum-1) return -1;
for(int i=0; i < g.vexnum; i++){
if(g.matrix[v][i] == 1) return i;
}
return -1;
}
void DFS(Graph g, int i){
if(visited[i] == 0){
visited[i] = 1;
cout<<g.vexs[i]<<" ";
}
int w = first_vertex(g,i);
for(;w>=0; w = next_vertex(g,i,w)){
if(!visited[w]) DFS(g,w);
}
}
int main(int argc, const char * argv[]) {
for(int i = 0; i < MAX; i++){
visited[i] = 0;
}
Graph g;
g= creat_graph();
for(int i = 0; i< g.vexnum; i++){
if(!visited[i]) DFS(g,i);
}
return 0;
}
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11