数据结构实验之图论二:图的深度遍历
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
请定一个无向图,顶点编号从0到n-1,用深度优先搜索(DFS),遍历并输出。遍历时,先遍历节点编号小的。
Input
输入第一行为整数n(0 < n < 100),表示数据的组数。 对于每组数据,第一行是两个整数k,m(0 < k < 100,0 < m < k*k),表示有m条边,k个顶点。 下面的m行,每行是空格隔开的两个整数u,v,表示一条连接u,v顶点的无向边。
Output
输出有n行,对应n组输出,每行为用空格隔开的k个整数,对应一组数据,表示DFS的遍历结果。
Example Input
1
4 4
0 1
0 2
0 3
2 3
Example Output
0 1 2 3
// ConsoleApplication23.cpp : 定义控制台应用程序的入口点。
//
#include <iostream>
#include <memory.h>
#define MAX 100
bool visited[MAX]={0};
using namespace std;
typedef struct {
int vex[MAX];
bool arc[MAX][MAX];
int numVex,numEdge;
}Graph;
void CreateGraph (Graph &G){//-----------------------创建无向图的邻接矩阵
int i,j,k,w;
cin >> G.numVex >> G.numEdge;
memset(G.arc,0,sizeof(bool)*MAX*MAX);
for(i=0;i<G.numVex;i++)
G.vex[i]=i;
for(i=0;i<G.numEdge;i++){
cin >> k >> w;
G.arc[k][w]=1;
G.arc[w][k]=1;
}
}
void DFS_Visit(Graph G,int begin){
if(0==begin) cout << G.vex[begin];
else cout << " " << G.vex[begin];
visited[begin]=true;
for(int i=0;i<G.numVex;i++){
if(G.arc[begin][i]==1 && visited[i]==false)
DFS_Visit(G,i);
}
}
void DFS(Graph G){
for(int i=0;i<G.numVex;i++)
if(!visited[i])
DFS_Visit(G,i);
}
int main(){
int n;
cin >> n;
while (n--){
Graph G;
CreateGraph(G);
memset(visited,0,sizeof(bool)*MAX);
DFS(G);
cout << endl;
}
return 0;
}
/***************************************************
User name: zhxw150244李政
Result: Accepted
Take time: 0ms
Take Memory: 240KB
Submit time: 2016-11-16 19:18:01
****************************************************/