06-图1 列出连通集 (25分)

06-图1 列出连通集 (25分)
06-图1 列出连通集 (25分)_第1张图片解题思路 :由于题目给的是非连通图,所以要考虑到BFS 和 DFS外面还需要嵌套一层循环

#include
#include
using namespace std;
typedef struct VNode
{
    int Nv,Ne;
    int Data[10][10];
}*MGraph;//建立邻接矩阵
typedef struct ENode
{
    int V1;
    int V2;
}*Edge;//边的定义

int* Visited = new int[10];

MGraph CreateGraph(int VertexNum);
void InsertEdge(MGraph Graph,Edge E);
MGraph BuildGraph();
void DFS(MGraph Graph,int n);
void BFS(MGraph Graph,int n);
int main()
{
    MGraph Graph;
    Graph = BuildGraph();
    int i;
    for(i = 0;i<Graph->Nv;i++)
        Visited[i]=0;
    for(i = 0;i<Graph->Nv;i++)
    {
        if(Visited[i]==0)
        {
            cout << "{"<<" ";
            DFS(Graph,i);
            cout << "}"<<endl;
        }
    }
    for(i = 0;i<Graph->Nv;i++)
        Visited[i]=0;
    for(i = 0;i<Graph->Nv;i++)
    {
        if(Visited[i]==0)
        {
            cout << "{"<<" ";
            BFS(Graph,i);
            cout << "}"<<endl;
        }
    }
    return 0;
}

MGraph CreateGraph(int VertexNum)
{
    MGraph Graph;
    Graph = new VNode;
    Graph->Nv = VertexNum;
    Graph->Ne = 0;
    int i,j;
    for(i = 0;i<Graph->Nv;i++)
        for(j=0;j<Graph->Nv;j++)
            Graph->Data[i][j] = 0;
    return Graph;
}
void InsertEdge(MGraph Graph,Edge E)
{
    Graph->Data[E->V1][E->V2] =1;
    Graph->Data[E->V2][E->V1] =1;
}
MGraph BuildGraph()
{
    MGraph Graph;
    Edge E;
    int VertexNum;
    int i;
    cin >> VertexNum;
    Graph = CreateGraph(VertexNum);
    cin >> Graph->Ne;
    if(Graph->Ne!=0)
    {
        E = new ENode;
        for(i=0;i<Graph->Ne;i++)
        {
            cin >> E->V1 >> E->V2;
            InsertEdge(Graph,E);
        }
    }
    return Graph;
}
void DFS(MGraph Graph,int n)
{
    int i;
    Visited[n]=1;
    cout <<n<<" ";
    for(i = 0;i<Graph->Nv;i++)
        if(Visited[i]==0&&Graph->Data[n][i]==1)
            DFS(Graph,i);
}
void BFS(MGraph Graph,int n)
{
    queue<int>Q;
    int i,Value;
    Visited[n] = 1;
    Q.push(n);
    while(!Q.empty())
    {
        Value = Q.front();
        Q.pop();
        cout <<Value<<" ";
        for(i=0;i<Graph->Nv;i++)
        {
            if(Visited[i]==0&&Graph->Data[Value][i]==1)//注意这里行为value不是n
            {
                Visited[i]=1;
                Q.push(i);
            }
        }
    }
}

你可能感兴趣的:(数据结构与算法第二版,数据结构第二版题目集,图论)