SDUT 2107 图的深度遍历

图的深度遍历

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

DQE:

纯水题233
 #include <iostream>
#include <cstdio>
using namespace std; #define MVN 110 typedef struct AdjMatrix
{
int w;
char *info;
}AM; typedef struct MGraph
{
int vex[MVN];
AM arc[MVN][MVN];
int vexn,arcn;
}MG; void creat(MG &G)
{
int i,j,k;
for(i=;i<G.vexn;i++)
for(j=;j<G.vexn;j++)
G.arc[i][j].w=;
for(k=;k<G.arcn;k++)
{
scanf("%d %d",&i,&j);
G.arc[i][j].w=G.arc[j][i].w=;
}
} void DFS(MG &G,bool *f,int i)
{
if(i==)
printf("%d",i);
else
printf(" %d",i);
f[i]=true;
int k;
for(k=;k<G.vexn;k++)
if(G.arc[i][k].w==&&f[k]==false)
DFS(G,f,k);
} int main()
{
int t;
scanf("%d",&t);
while(t--)
{
MG G;
scanf("%d %d",&G.vexn,&G.arcn);
creat(G);
bool visited[MVN]={false};
DFS(G,visited,);
printf("\n");
}
return ;
} /***************************************************
User name: ***
Result: Accepted
Take time: 0ms
Take Memory: 168KB
Submit time: 2016-11-18 20:26:05
****************************************************/
上一篇:数据结构实验之图论二:图的深度遍历(SDUT 2107)(简单DFS)


下一篇:数据结构——图的深度优先遍历(邻接矩阵表示+java版本)