Menu
Coddy logo textTech

크기

Coddy의 그래프 - 자료구조 시리즈 #9 코스 레슨 — 14개 중 9번째.

Graph에 마지막으로 필요한 것은 정점이 몇 개인지 알려주는 빠른 방법입니다. vertices는 정점 키를 키로 하는 맵이므로, 그 답은 단순히 해당 맵의 크기입니다.

이것은 간선이 아니라 정점의 수를 센다는 점에 유의하세요. 빈 그래프에서 addEdge(1, 2)를 호출하면 두 개의 정점과 하나의 간선이 추가되므로 크기는 2가 됩니다. 나중에 간선을 제거해도 크기는 변하지 않습니다. 정점은 명시적으로 제거될 때까지 남아 있습니다.

challenge icon

챌린지

쉬움

Graph 클래스에 size 메서드를 추가하세요.

이 메서드는 입력을 받지 않으며 현재 그래프에 있는 정점의 수(vertices의 항목 수)를 반환합니다.

직접 해보기

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "graph.h"

static int _cmp_int(const void* a, const void* b) {
    int ai = *(const int*)a, bi = *(const int*)b;
    return (ai > bi) - (ai < bi);
}

int main() {
    Graph g;
    Graph_init(&g);
    char line[1024];
    while (fgets(line, sizeof(line), stdin)) {
        line[strcspn(line, "\r\n")] = '\0';
        char* cmd = strtok(line, " \t");
        if (!cmd) continue;
        if (strcmp(cmd, "verticesEmpty") == 0) { printf("%s\n", g.vertexCount == 0 ? "true" : "false"); }
        if (strcmp(cmd, "hasVertex") == 0) { char* arg = strtok(NULL, " \t"); if (arg) printf("%s\n", Graph_indexOf(&g, atoi(arg)) != -1 ? "true" : "false"); }
        if (strcmp(cmd, "addVertex") == 0) { char* arg = strtok(NULL, " \t"); if (arg) Graph_addVertex(&g, atoi(arg)); }
        if (strcmp(cmd, "addEdge") == 0) { char* a1 = strtok(NULL, " \t"); char* a2 = strtok(NULL, " \t"); if (a1 && a2) Graph_addEdge(&g, atoi(a1), atoi(a2)); }
        if (strcmp(cmd, "degree") == 0) {
            char* arg = strtok(NULL, " \t");
            if (arg) {
                int k = atoi(arg);
                int ki = Graph_indexOf(&g, k);
                printf("%d\n", ki == -1 ? 0 : g.vertices[ki].n);
            }
        }
        if (strcmp(cmd, "hasEdge") == 0) { char* a1 = strtok(NULL, " \t"); char* a2 = strtok(NULL, " \t"); if (a1 && a2) printf("%s\n", Graph_hasEdge(&g, atoi(a1), atoi(a2)) ? "true" : "false"); }
        if (strcmp(cmd, "neighbors") == 0) {
            char* arg = strtok(NULL, " \t");
            if (arg) {
                int buf[MAX_NEIGHBORS];
                int n = Graph_getNeighbors(&g, atoi(arg), buf);
                qsort(buf, n, sizeof(int), _cmp_int);
                for (int i = 0; i < n; i++) {
                    if (i > 0) printf(" ");
                    printf("%d", buf[i]);
                }
                printf("\n");
            }
        }
        if (strcmp(cmd, "removeEdge") == 0) { char* a1 = strtok(NULL, " \t"); char* a2 = strtok(NULL, " \t"); if (a1 && a2) Graph_removeEdge(&g, atoi(a1), atoi(a2)); }
        if (strcmp(cmd, "size") == 0) { printf("%d\n", Graph_size(&g)); }
    }
    return 0;
}

그래프 - 자료구조 시리즈 #9의 모든 레슨