Obter Vizinhos
Lição 7 de 14 do curso Grafos - Série de Estruturas de Dados #9 da Coddy.
Algoritmos como BFS, DFS e caminho mais curto não olham para o mapa bruto: eles perguntam "quais são os vizinhos deste vértice?" e percorrem a resposta. Nosso método getNeighbors expõe isso.
Se o vértice estiver no grafo, retorne sua lista de vizinhos. Retorne uma cópia se você quiser que os chamadores modifiquem o resultado sem quebrar o grafo (este é um bom hábito). Se o vértice não existir, retorne uma lista vazia em vez de causar um erro. Isso mantém o código do cliente simples: ele sempre pode iterar sobre o resultado.
Desafio
FácilAdicione um método getNeighbors à classe Graph.
Ele recebe um inteiro key e retorna uma lista de seus vizinhos:
- Se
keyestiver emvertices, retorne sua lista de vizinhos (uma cópia está correta). - Se
keynão estiver no grafo, retorne uma lista vazia.
Experimente você mesmo
#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;
}
Todas as lições de Grafos - Série de Estruturas de Dados #9
2Projeto de Grafo
Classe GrafoAdicionar VérticeAdicionar ArestaPossui ArestaObter VizinhosRemover ArestaTamanho