图的深度遍历
Time Limit: 1000MSMemory Limit: 65536KB
ProblemDescription
请定一个无向图,顶点编号从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的遍历结果。
ExampleInput
1   4 4   0 1   0 2   0 3   2 3  ExampleOutput
0 1 2 3  Hint
 #include <cstdio>
    #include <cstring>
    using namespace std;
bool a[105][105],vis[105];
bool top;
int n,m;
void dfs(int x)
{
    if(!top)printf(" ");
    top=0;
    printf("%d",x);
    for(int i=x;i<n;i++)
    {
    if(a[x][i]&&vis[i]==0)
    {
        vis[i] = 1;
        dfs(i);
    }
    }
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
    scanf("%d%d",&n,&m);
    memset(a,0,sizeof(a));
    memset(vis,0,sizeof(vis));
    for(int i=0;i<m;i++)
    {
    int v,u;
    scanf("%d%d",&u,&v);
    a[u][v]= a[v][u]=1;
    }
    top = 1;
    dfs(0);
    printf("\n");
    }
    return 0;
}
/***************************************************
User name: jk160505徐红博
Result: Accepted
Take time: 0ms
Take Memory: 112KB
Submit time: 2017-02-15 09:41:53
****************************************************/ 
京公网安备 11010502036488号