06-图1 列出连通集 (25分)
给定一个有N个顶点和E条边的无向图,请用DFS和BFS分别列出其所有的连通集。假设顶点从0到N−1编号。进行搜索时,假设我们总是从编号最小的顶点出发,按编号递增的顺序访问邻接点。
输入格式:
输入第1行给出2个整数N(0)和E,分别是图的顶点数和边数。随后E行,每行给出一条边的两个端点。每行中的数字之间用1空格分隔。
输出格式:
按照"{ v1 v2 ... vk }"的格式,每行输出一个连通集。先输出DFS的结果,再输出BFS的结果。
输入样例:
8 6 0 7 0 1 2 0 4 1 2 4 3 5
输出样例:
{ 0 1 4 2 7 } { 3 5 } { 6 } { 0 1 2 7 4 } { 3 5 } { 6 }
提测代码:
矩阵实现:
#include <stdlib.h> #include <stdio.h> #define ERROR -1 typedef int ElemType; typedef int Position; typedef struct QNode* Queue; struct QNode { ElemType*data; Position front; Position rear; int maxSize; }; Queue CreateQueue(int maxSize) { Queue Q = (Queue)malloc(sizeof(struct QNode)); Q->data = (ElemType*)malloc(sizeof(ElemType)*maxSize); Q->front = 0; Q->rear = 0; Q->maxSize = maxSize; return Q; } void DestroyQueue(Queue Q) { if (Q) { if (Q->data) { free(Q->data); } free(Q); } } int IsFullQueue(Queue Q) { return (Q->front == (Q->rear + 1) % Q->maxSize); } void Enqueue(Queue Q, ElemType item) { if (IsFullQueue(Q)) { return; } Q->rear = (Q->rear + 1) % Q->maxSize; Q->data[Q->rear] = item; } int IsEmptyQueue(Queue Q) { return (Q->front == Q->rear); } ElemType Dequeue(Queue Q) { if (IsEmptyQueue(Q)) { return ERROR; } Q->front = (Q->front + 1) % Q->maxSize; return Q->data[Q->front]; } #define MAX 10 Queue Q = NULL; int matrix[MAX][MAX]; int dfs_visited[MAX]; int bfs_visited[MAX]; int N, E; void DFS(int nIndex) { dfs_visited[nIndex] = 1; printf(" %d", nIndex); for (int i = 0; i < N; ++i) if (matrix[nIndex][i] && !dfs_visited[i]) DFS(i); } void BFS(int nIndex) { Enqueue(Q, nIndex); while (!IsEmptyQueue(Q)) { int temp = Dequeue(Q); if (!bfs_visited[temp]) { printf(" %d", temp); bfs_visited[temp] = 1; } for (int i = 0; i < N; ++i) { if (matrix[temp][i] && !bfs_visited[i]) { printf(" %d", i); bfs_visited[i] = 1; Enqueue(Q, i); } } } } int main() { Q = CreateQueue(MAX + 1); for (int i = 0; i < MAX; ++i) { dfs_visited[i] = 0; bfs_visited[i] = 0; } scanf("%d %d", &N, &E); int nIndex1, nIndex2; for (int i = 0; i < E; ++i) { scanf("%d %d", &nIndex1, &nIndex2); matrix[nIndex1][nIndex2] = 1; matrix[nIndex2][nIndex1] = 1; } for (int i = 0; i < N; ++i) { if (!dfs_visited[i]) { putchar('{'); DFS(i); printf(" } "); } } for (int i = 0; i < N; ++i) { if (!bfs_visited[i]) { putchar('{'); BFS(i); printf(" } "); } } return 0; }
提测结果: