[PTA] 4-14 Count Connected Components (20分)

    这次偷懒没有写read函数,此题是非常水的搜索题,是图论的基本功,可以用dfs,也可以用并查集。

   

#include <stdio.h>
#include <stdlib.h>

typedef enum {false, true} bool;
#define MaxVertexNum 10  /* maximum number of vertices */
typedef int Vertex;      /* vertices are numbered from 0 to MaxVertexNum-1 */

typedef struct AdjVNode *PtrToAdjVNode; 
struct AdjVNode{
    Vertex AdjV;
    PtrToAdjVNode Next;
};

typedef struct Vnode{
    PtrToAdjVNode FirstEdge;
} AdjList[MaxVertexNum];

typedef struct GNode *PtrToGNode;
struct GNode{  
    int Nv;
    int Ne;
    AdjList G;
};
typedef PtrToGNode LGraph;

LGraph ReadG(); /* details omitted */

int CountConnectedComponents( LGraph Graph );

int main()
{
    LGraph G = ReadG();
    printf("%d\n", CountConnectedComponents(G));

    return 0;
}

int visit[MaxVertexNum];
void dfs(LGraph Graph,int v);

int CountConnectedComponents( LGraph Graph )
{
	int i;
	int cnt=0;
	for(i=0;i<Graph->Nv;i++){
		visit[i]=0;
	}
	for(i=0;i<Graph->Nv;i++){
		if(!visit[i]){
			dfs(Graph,i);
			cnt++;
		}
	} 
	return cnt;
}

void dfs(LGraph Graph,int v)
{
	visit[v]=1;
	PtrToAdjVNode p=Graph->G[v].FirstEdge;
	while(p){
		int i=p->AdjV;
		if(!visit[i])dfs(Graph,i);
		p=p->Next;
	}
}

/* Your function will be put here */


你可能感兴趣的:([PTA] 4-14 Count Connected Components (20分))