Its connectivity graph traversal

[Problem Description]
The adjacency matrix A of FIG input, determines the number of connected components of this graph.
[Form] input
the number n of the first node of FIG behavior, the behavior of the contents after n adjacency matrix, and n represents the number of each row. Where A [i] [j] = 1 represents two adjacent nodes, and A [i] [j] = 0 indicates no adjacency relationship between two nodes.
[] Output form
the output of this number of connected components of FIG.
[Sample input]
. 5
0 0 0. 1. 1
. 1. 1 0 0 0
. 1. 1 0 0 0
0 0 0 0. 1
0 0 0 0. 1
[output] Sample
2
[] Example Description
adjacency matrix on the diagonal elements are represented by 0. (Single independent node, i.e. other nodes and the edges are not connected, communication can be considered a component)

#include <bits/stdc++.h>
using namespace std;
#define MAX 200
typedef struct
{
    int arcs[MAX][MAX];
    int num;
    int flag[MAX*MAX];
} adjmatrix;
adjmatrix G;
void creat(adjmatrix *G)
{
    cin>>(*G).num;
    for(int i=0; i<(*G).num; i++)
    {
        for(int j=0; j<(*G).num; j++)
        {
            cin>>(*G).arcs[i][j];
        }
    }
}
void dfs(int x)     //将所有与点y连接的点标记,认为在一个连通分量
{
    for(int i=0; i<G.num; i++)
    {
        if(G.flag[i]==0&&G.arcs[x][i]==1)
        {
            G.flag[i]=1;
            dfs(i);     //深度优先遍历,递归处理与点i在同一个连通分支的点
        }
    }
}
void depthsearchlink()
{
    int sum=0,i;
    for(i=0; i<G.num; i++)
    {
        if(G.flag[i]==0) //遇到新的连通分支
        {
            G.flag[i]=1;
            dfs(i);//下一个开始
            sum++;
        }
    }
    cout<<sum;
}
int main()
{
    creat(&G);
    depthsearchlink();
    return 0;
}


Guess you like

Origin blog.csdn.net/weixin_44355876/article/details/95310897