Größe
Lektion 9 von 14 im Kurs Graphen - Datenstrukturen-Serie #9 von Coddy.
Das Letzte, was der Graph benötigt, ist eine schnelle Möglichkeit, uns mitzuteilen, wie viele Vertices er hat. Da vertices eine Map ist, die nach dem Vertex-Key indiziert ist, ist die Antwort einfach die Größe dieser Map.
Beachten Sie, dass dies Vertices zählt, nicht Kanten. Der Aufruf von addEdge(1, 2) bei einem leeren Graphen fügt zwei Vertices und eine Kante hinzu, sodass die Größe auf 2 steigt. Das spätere Entfernen der Kante ändert die Größe nicht: Die Vertices bleiben bestehen, bis sie explizit entfernt werden.
Aufgabe
EinfachFügen Sie der Klasse Graph eine Methode size hinzu.
Sie nimmt keine Eingabe entgegen und gibt die Anzahl der aktuell im Graphen vorhandenen Knoten zurück (die Anzahl der Einträge in vertices).
Probier es selbst
#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;
}