对于给定的无向图以及图中的两个顶点,计算两个顶点所在的连通分量中的顶点数,并且判断这两个顶点之间是否有路径。
输入格式:
第一行是不超过20
的正整数N
,表示图有N
个顶点,顶点的编号即0
~N-1
;
接下来N
行,是N*N
的邻接矩阵,矩阵的元素间用空格分隔;
最后一行是用空格隔开的两个顶点编号v
和w
输出格式:
第一行输出v
所在的连通分量的顶点数
第二行输出w
所在的连通分量的顶点数
第三行,若v
和w
之间有路径,则输出Yes
,否则输出No
注意:当v
和w
是同一个顶点时,认为v
和w
之间是有路径的。
输入样例:
对于这个图:
8
0 1 1 0 0 0 0 1
1 0 0 0 1 0 0 0
1 0 0 0 1 0 0 0
0 0 0 0 0 1 0 0
0 1 1 0 0 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0
1 3
输出样例:
5
2
No
用BFS或DFS进行遍历
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MaxVertexNum 20
typedef struct GNode* PtrToGNode;
struct GNode {
int Nv;
int G[MaxVertexNum][MaxVertexNum];
};
typedef PtrToGNode MGraph;
MGraph CreateGraph() {
int v, w;
int Nv;
scanf("%d", &Nv);
MGraph Graph = (MGraph)malloc(sizeof(struct GNode));
Graph->Nv = Nv;
for (v = 0; v < Nv; v++)
for (w = 0; w < Nv; w++)
scanf("%d", &Graph->G[v][w]);
return Graph;
}
int Visited[MaxVertexNum];
/*void Visit(int v) {
printf(" %d", v);
}*/
int count = 0;
/*void DFS(MGraph Graph, int v) {
if (!Visited[v]) {
int i;
//Visit(v);
Visited[v] = 1;
count++;
for (i = 0; i < Graph->Nv; i++) {
if (!Visited[i] && Graph->G[v][i]) {
DFS(Graph, i);
}
}
}
}*/
void BFS(MGraph Graph, int v) {
if (!Visited[v]) {
int i;
int front = 0, rear = 0;
int Queue[MaxVertexNum];
Queue[++rear] = v;
Visited[v] = 1;
while (rear != front) {
int w;
w = Queue[++front];
//Visit(w);
count++;
for (i = 0; i < Graph->Nv; i++) {
if (!Visited[i] && Graph->G[w][i]) {
Queue[++rear] = i;
Visited[i] = 1;
}
}
}
}
}
int main() {
int v, w,temp;
MGraph Graph = CreateGraph();
scanf("%d%d", &v, &w);
BFS(Graph, v);
//DFS(Graph, v);
printf("%d\n", count);
temp = count;
count = 0;
if (Visited[w]) {
printf("%d\n", temp);
printf("Yes");
}
else {
BFS(Graph, w);
//DFS(Graph, w);
printf("%d\n", count);
printf("No");
}
return 0;
}