Menu
Coddy logo textTech

Add Edge

Lesson 5 of 14 in Coddy's Graphs - Data Structures Series #9 course.

An edge connects two vertices. Since our graph is undirected, the connection goes both ways: if u and v are connected, then u appears in v's neighbor list and v appears in u's.

Before wiring anything, make sure both vertices exist by calling addVertex on each (it is a no-op if they already exist). Then push each one onto the other's neighbor list. Skip a duplicate push if the edge is already there. For a self-loop (u == v), add it only once.

Now let's write it.

challenge icon

Challenge

Easy

Add a method addEdge to the Graph class.

It takes two integers u and v and connects them in both directions:

  • Make sure both u and v exist (use addVertex if not).
  • Add v to u's neighbor list (only if it is not already there).
  • Add u to v's neighbor list (only if it is not already there). If u == v, do not add it a second time.

Try it yourself

#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);
            }
        }
    }
    return 0;
}

All lessons in Graphs - Data Structures Series #9