Determine whether the undirected graph is connected by DFS and BFS

basic definition

Undirected graph: A graph without direction
Connected graph: Any two vertices can be connected directly or through other vertices, then it is a connected graph, which needs to be distinguished from a complete graph (a complete graph requires any two vertices to have a direct path)

The basic method of traversing the graph to determine whether it is connected

Some steps of DFS and BFS start from a vertex, and then determine whether the vertex is accessed, and whether the vertex is related to other vertices. If it is related and has not been accessed, it will be accessed down. If the undirected graph is connected , then this process will traverse all nodes in turn. So through this feature, you can set a global variable count to record to see if the last count value is the same as the number of vertices. If they are the same, it means that it is an undirected connected graph, and vice versa.

int count = 0;
void DFS(MGrap G. int i)
{
    int j = 0;
    visited[i] = 1;
    count++;
    for(j=0; j<G.numVertexes; j++)
    {
        if(G.arc[i][j]==1 && !visited[j])//i和j有关系相邻,并且j顶点没有被访问过
        {
            DFS(G, j);
        }
    }
}
int count = 0;
void BFS(MGrap G)
{
    int i,j;
    Queue Q;
    for(i=0; i<G.numVertexes; i++)/*初始化访问数组*/
    {
        visited[i] = -1;
    }
    InitQueue(&Q);
    for(i=0; i<G.numVertexes; i++)
    {
        if(!visited[i])
        {
            visited[i] = 1;
            printf("%c",G.vexs[i]);
            EnQueue(&Q,i);/*入队操作*/
            while(!QueueEmpty(Q))
            {
                DeQueue(&Q, &i);
                for(j=0; j<G.numVertexes; j++)
                {
                    /* 判断当前的节点与其他节点的关系 */
                    if(G.arc[i][j]==1 && !visited[j])
                    {
                        if(i==0)/*首先遍历的节如果和其他边有关系的话要加上*/
                        {
                            count++;
                        }
                        visited[j] = 1;
                        count++;
                        EnQueue(&Q,j);
                    }
                }
            }
        }
    }
}


PS: This code was added by myself, and I don't know if it is right or not. If it's not right, I hope you guys can help me out.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326362313&siteId=291194637