数据结构实验之图论二:图的深度遍历

#include <bits/stdc++.h>

using namespace std;
int k,m,n;
int mmp[110][110];  //建立邻接矩阵存储图
int vis[110];       //储存已遍历的结点

void DFS(int n)
{
    if(n==0)
        cout << n;
    else
        cout << ' '<< n;
    vis[n] = 1;
    for(int i=0; i<k; i++)
    {
        if(!vis[i] && mmp[n][i])
        {
            DFS(i);
        }
    }
}

int main()
{
    int t,u,v;
    cin >> t;
    while(t--)
    {
        cin >> k >> m;
        memset(mmp,0,sizeof(mmp));
        memset(vis,false,sizeof(vis));
        while(m--)
        {
            cin >> u >> v;
            mmp[u][v] = mmp[v][u] = 1;
        }
        DFS(0);
        cout << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42963463/article/details/81673372