Description
求一个图的连通分量
Input
n n n 顶点数( n n n<= 100 100 100)
边
Output
连通分量
Sample Input
8
6 3
1 2
2 5
5 4
4 1
8 7
0 0
Sample Output
4
思路
这里有五种方法,分别是 d f s + 邻 接 表 , b f s + 邻 接 表 , d f s + 邻 接 矩 阵 , b f s + 邻 接 矩 阵 , b f s + 邻 接 表 + S T L ( 队 列 ) 。 dfs+邻接表,bfs+邻接表,dfs+邻接矩阵,bfs+邻接矩阵,bfs+邻接表+STL(队列)。 dfs+邻接表,bfs+邻接表,dfs+邻接矩阵,bfs+邻接矩阵,bfs+邻接表+STL(队列)。
首先是两种读入:
邻接表
struct whw
{
int x,y;
}a[10001];
/*---------------------------------------------------------*/
scanf("%d%d",&x,&y);
while (x && y)
{
a[++m]=(whw){
y,h[x]};h[x]=m;
a[++m]=(whw){
x,h[y]};h[y]=m;//因为是无向图,所以x到y和y到x都要赋值
scanf("%d%d",&x,&y);
}
邻接矩阵
int h[1005][1005];
/*---------------------------------------------------------*/
scanf("%d%d",&x,&y);
while (x && y)
{
h[x][y]=h[y][x]=1;//上面
scanf("%d%d",&x,&y);
}
还有用 S T L STL STL时要注意:
库: < q u e u e > <queue> <queue>
定义int类型的队列(wh): q u e u e < i n t