인접 정점 가져오기
Coddy의 그래프 - 자료구조 시리즈 #9 코스 레슨 — 14개 중 7번째.
BFS, DFS, 최단 경로와 같은 알고리즘은 원본 지도를 직접 보지 않습니다. 대신 "이 정점의 이웃은 무엇인가?"라고 묻고 그 결과를 따라갑니다. 우리의 getNeighbors 메서드가 바로 그 기능을 제공합니다.
정점이 그래프에 존재하면 해당 정점의 이웃 리스트를 반환합니다. 호출자가 그래프 구조를 깨뜨리지 않고 결과를 수정할 수 있도록 하려면 복사본을 반환하는 것이 좋습니다(이는 좋은 습관입니다). 정점이 존재하지 않는 경우, 프로그램이 중단되는 대신 빈 리스트를 반환하세요. 그러면 클라이언트 코드가 항상 결과를 반복문으로 처리할 수 있어 코드가 단순해집니다.
챌린지
쉬움Graph 클래스에 getNeighbors 메서드를 추가하세요.
이 메서드는 정수 key를 인자로 받아 해당 정점의 이웃 리스트를 반환합니다:
- 만약
key가vertices에 존재한다면, 해당 정점의 이웃 리스트를 반환합니다 (복사본을 반환해도 무방합니다). - 만약
key가 그래프에 존재하지 않는다면, 빈 리스트를 반환합니다.
직접 해보기
#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");
}
}
}
return 0;
}