CS/자료구조 & 알고리즘

[C] 인접 행렬로 그래프 구현

ShovelingLife 2022. 6. 11. 20:35
// 인접 행렬
 
// 그래프를 인접행렬로 표현하기
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX 30
 
typedef struct graphType {
    int n; // 정점개수
    int adjMatrix_Arr[MAX_VERTEX][MAX_VERTEX];
}graphType;
 
// 공백. 그래프를 생성하는 연산
void CreateGraph(graphType* ptr) {
    ptr->n = 0; // 정점 개수를 0으로 초기화
    for (int i = 0; i < MAX_VERTEX; i++) {
        for (int j = 0; j < MAX_VERTEX; j++) {
            ptr->adjMatrix_Arr[i][j] = 0;
        }
    }
}
 
// 그래프에 정점 n을 삽입하는 연산
void InsertVertex(graphType* ptr, int n) {
    if (((ptr->n) + 1) > MAX_VERTEX)  printf("\n 그래프 정점의 개수를 초과했습니다!");
    ptr->n++; //정점의 개수 n을 하나씩 증가
}
 
// 그래프에 간선 (u,v)를 삽입하는 연산
void  InsertEdge(graphType* ptr, int u, int v) {
    if (u >= ptr->n || v >= ptr->n)  printf("\n 그래프에 없는 정점입니다!");
    ptr->adjMatrix_Arr[u][v] = 1;
}
 
void PrintGraph(graphType* ptr) {
    char letter = 65;
    for (int i = 0; i < (ptr->n); i++) {
        printf("\n\t\t");
        printf("%c", letter + i);
        for (int j = 0; j < (ptr->n); j++) {
            printf(" %3d", ptr->adjMatrix_Arr[i][j]);
        }
    }
}
 
int main() {
    char letter = 65;
    graphType* G1, * G2, * G3, * G4;
    G1 = (graphType*)malloc(sizeof(graphType));
    G2 = (graphType*)malloc(sizeof(graphType));
    G3 = (graphType*)malloc(sizeof(graphType));
    G4 = (graphType*)malloc(sizeof(graphType));
 
    CreateGraph(G1);
    CreateGraph(G2);
    CreateGraph(G3);
    CreateGraph(G4);
 
    // G1그래프 설정하기
    for (int i = 0; i < 4; i++) {
        InsertVertex(G1, i);
    }
 
    InsertEdge(G1, 0, 1); InsertEdge(G1, 0, 3); // A
    InsertEdge(G1, 1, 0); InsertEdge(G1, 1, 2); InsertEdge(G1, 1, 3); // B
    InsertEdge(G1, 2, 1); InsertEdge(G1, 2, 3); // C
    InsertEdge(G1, 3, 0); InsertEdge(G1, 3, 1); InsertEdge(G1, 3, 2); // D
    printf("\nG1의 인접 행렬\t    A   B   C   D");
    PrintGraph(G1); printf("\n");
 
    // G2 그래프 설정하기
    for (int i = 0; i < 3; i++) {
        InsertVertex(G2, i);
    }
 
    InsertEdge(G2, 0, 1); InsertEdge(G2, 0, 2); // A
    InsertEdge(G2, 1, 0); InsertEdge(G2, 1, 2); // B
    InsertEdge(G2, 2, 0); InsertEdge(G2, 2, 1); // C
 
    printf("\nG2의 인접 행렬\t    A   B   C");
    PrintGraph(G2); printf("\n");
 
    // G3 그래프 설정하기
    for (int i = 0; i < 4; i++) {
        InsertVertex(G3, i);
    }
 
    InsertEdge(G3, 0, 1); InsertEdge(G3, 0, 3); // A
    InsertEdge(G3, 1, 2); InsertEdge(G3, 1, 3); // B
    InsertEdge(G3, 2, 3); // C
       
       printf("\nG3의 인접 행렬\t    A   B   C   D");
    PrintGraph(G3); printf("\n");
 
    // G4 그래프 설정하기
    for (int i = 0; i < 3; i++) {
        InsertVertex(G4, i);
    }
 
    InsertEdge(G4, 0, 1); InsertEdge(G4, 0, 2); // A
    InsertEdge(G4, 1, 0); InsertEdge(G4, 1, 2); // B
 
       printf("\nG4의 인접 행렬\t    A   B   C");
    PrintGraph(G4); printf("\n");
}