标签:pat
轻松愉快的邻接矩阵,“现在空间还是问题么?”
#include <stdio.h> #include <malloc.h> #include <queue> using namespace std; int* CreateMatrixGraph(const int& N) { int* graph = (int*) malloc(sizeof(int) * N * N); for (int i = 0;i < N * N; i++) { graph[i] = 0; } return graph; } bool IsMatrixConnected(const int& a, const int& b, int* graph, const int& N) { if (a == b) { return false; } return (graph[a * N + b]); } void MatrixConnect(const int& a, const int& b, int* graph, const int& N) { if (IsMatrixConnected(a, b, graph, N)) { printf("ERROR : %d AND %d ALREADY CONNECTED\n", a, b); return; } if (a == b) { printf("ERROR : THE SAME VERTICE\n"); return; } graph[a * N + b] = 1; graph[b * N + a] = 1; } void GetAdjoinVertice(const int& vertice, int* graph, int* adjoinVertice, int N) { int currentIndex = 0; for (int i = 0; i < N; i++) { if (graph[vertice * N + i] == 1) { adjoinVertice[currentIndex++] = i; } } } void DFS(int* graph, int vertice, bool* isVisited, int N) { printf("%d ", vertice); isVisited[vertice] = true; int* adjoinVertice = (int*) malloc(sizeof(int) * N); for (int i = 0; i < N; i++) { adjoinVertice[i] = -1; } GetAdjoinVertice(vertice, graph, adjoinVertice, N); int i = 0; while (adjoinVertice[i] != -1) { if (!isVisited[adjoinVertice[i]]) { DFS(graph, adjoinVertice[i], isVisited, N); } i++; } free(adjoinVertice); } void BFS(int* graph, int vertice, bool* isVisited, int N) { queue<int> t; t.push(vertice); isVisited[vertice] = true; while (!t.empty()) { int currentVertice = t.front(); t.pop(); printf("%d ", currentVertice); int* adjoinVertice = (int*) malloc(sizeof(int) * N); for (int i = 0; i < N; i++) { adjoinVertice[i] = -1; } GetAdjoinVertice(currentVertice, graph, adjoinVertice, N); int i = 0; while (adjoinVertice[i] != -1) { if (!isVisited[adjoinVertice[i]]) { t.push(adjoinVertice[i]); isVisited[adjoinVertice[i]] = true; } i++; } } } void MatrixComponentsSearch(int* graph, bool* isVisited, int N, int function) { for (int i = 0; i < N; i++) { if (!isVisited[i]) { if (function == 1) { printf("{ "); DFS(graph, i, isVisited, N); printf("}\n"); } else { printf("{ "); BFS(graph, i, isVisited, N); printf("}\n"); } } } } int main(void) { int N; int E; scanf("%d %d", &N, &E); int* graph = CreateMatrixGraph(N); for (int i = 0; i < E; i++) { int vertical; int horizontal; scanf("%d %d", &vertical, &horizontal); MatrixConnect(vertical, horizontal, graph, N); } bool* isVisited = (bool*) malloc(sizeof(bool) * N); for (int i = 0; i < N; i++) { isVisited[i] = false; } MatrixComponentsSearch(graph, isVisited, N, 1); for (int i = 0; i < N; i++) { isVisited[i] = false; } MatrixComponentsSearch(graph, isVisited, N, 2); return 0; }
06-图1. List Components (25) (邻接矩阵实现)
标签:pat
原文地址:http://blog.csdn.net/qq_19672579/article/details/46279323