개발/C,C++

C - 인접행렬로 그래프 구현하기 (알고리즘)

ebang 2022. 12. 16. 23:00
반응형
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//인접 행렬로 그래프 표현하기


/*
함수 기능 명세
[public]
Makegraph : 문제에서 요구하는 대로 그래프를 완성한다.
makeEdge : 두 노드를 받아, 맞게 vertex 를 표현한다.
print_graph  : 그래프에서 한 노드에 연결된 인접 행렬을 모두 표시한다.
modify_weight : 노드 간의 vertex의 weight를 조정하되, 없으면 만들고 0이면 삭제한다.
   0일 때: delete_vertex
   0이 아닐 떄: 양쪽으로 modify_weight_utils
[private]
modify_weight_utils : 한쪽으로 node1에서 node2를 지운다 .

*/
void makeEdge(int (* graph)[7], int row, int col, int w);

void makeGraph(int (* graph)[7])
{
    makeEdge(graph, 1, 2, 1);
    makeEdge(graph, 1, 3, 1);
    makeEdge(graph, 1, 4, 1);
    makeEdge(graph, 1, 6, 2);
    makeEdge(graph, 2, 3, 1);
    makeEdge(graph, 3, 5, 4);
    makeEdge(graph, 5, 6, 3);
    makeEdge(graph, 5, 5, 4);
}

void modify_weight_utils(int (* graph)[7], int node1, int node2, int weight, int n)
{
    graph[node1][node2] = weight; // 가중치가 0이어도 새로 생기고 0을 대입해도 삭제되고, 자기 자신과의 vertex도 문제되지 않는다. 
}

void modify_weight(int (* graph)[7], int node1, int node2, int weight, int n)
{
    if (node1 >= n || node2 >= n || node1 < 1 || node2 < 1)
    {
        printf("-1");
        return;
    }
    modify_weight_utils(graph, node1, node2, weight, n);
    modify_weight_utils(graph, node2, node1, weight, n);
}

void makeEdge(int (* graph)[7], int row, int col, int w)
{
    graph[row][col] = w;
    graph[col][row] = w;
}

void   print_graph(int  (* graph)[7], int row, int n)
{
    int flag = 1;
    for (int i = 1; i < n; i++)
    {
        if (graph[row][i] != 0)
        {
            printf(" %d %d", i, graph[row][i]);
            flag = 0;
        }
    }
    printf("\n");

}

int main()
{
    int graph[7][7];
    int r = 7, c = 7;
    int n = 7;//노드의 수
    int n1, n2, w;
    char order;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            graph[i][j] = 0;
        }
    }

    makeGraph(graph);
    while (1)
    {
        scanf("%c", &order);
        if (order == 'a')
        {
            scanf("%d", &n1);
            if (n1 < 1 || n1 > 6)
                printf("-1");
            else
                print_graph(graph, n1, n);
        }
        else if (order == 'm')
        {
            scanf("%d %d %d", &n1, &n2, &w);
            modify_weight(graph, n1, n2, w, n);
        }
        else if (order = 'q')
        {
            break;
        }
        getchar();
    }
}
반응형