Vertices and edges
Beginner · 6 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A graph is a set of things (vertices, also called nodes or dots) and the links between them (edges, the lines). It is the plain way to describe anything where things are connected: friends, roads, web pages or tasks that depend on each other.
Practical use cases
- Web app: Modelling a metro map. A transit app shows stations and the lines between them. Each station is a vertex and each stretch of track is an edge. With that model the app can answer questions like "how do I get from Dwarka to Rajiv Chowk?" using standard methods instead of special code per city.
- Web app: Friends and followers in a social app. Every user is a vertex, and every friendship or follow is an edge. Features such as "mutual friends" and "people you may know" become simple questions about the dots and lines. Adding a new feature does not need a new database design.
- System: The web, networks and dependencies. Web pages with links form a graph that search engines crawl. Computer networks, package managers with their dependencies and build systems are all dots and lines too, which is why one set of methods works across so many tools.
The story: The Dots and Lines of Zoya's Notebook
Zoya was new in town, and her first job was to learn how to reach her cousin's house. Grandpa Bhaskar gave her a notebook and said, "Do not draw the whole city. Draw only what matters." Zoya frowned. A city has trees, shops, dogs, puddles, hawkers, cows asleep in the middle of the road... what matters? She chewed her pencil for a long, long time.
So she made a rule. For every important place (her house, the bus stop, the temple, the cousin's lane) she drew a dot. For every road that joined two places directly, she drew a line between their dots. Nothing else. No colours, no tiny shops.
Grandpa smiled. "You just invented a graph. The dots are vertices and the lines are edges." Suddenly questions became easy: Which places touch the bus stop? Is there a way from home to the cousin? Zoya found her way using a drawing that fit on one page.
How to spot this problem, and where you need it
Your data is about relationships between things, not just rows in a list, and questions like "how are these two connected?" are hard to answer with ordinary tables and loops.
Signs you need it
- A table holds pairs such as user_id and friend_id, or from_city and to_city, and you keep joining it to itself.
- Questions ask about paths, connections, reachability or "who is linked to whom".
- You draw the problem on paper as dots and arrows to make sense of it.
Where to use it in a project
- Social features such as friend suggestions, mutual-friend counts and follow recommendations between users.
- Maps, transit routes, delivery networks and dependency lists between modules or tasks.
The solution
Decide what the dots are (users, stations, pages, tasks) and what a line means (friend, track, link, depends-on). Store the lines either as a list of pairs or as a list of neighbours per dot. After that, use standard graph methods for walking, searching and routing, instead of inventing logic for each question.
Payoff: Before: repeated self-joins and one-off code for each connection question. After: one simple model that answers paths, mutual links and reachability.
Explain it like I am 8
Draw some dots on paper. Each dot is a thing, like a friend. Now draw a line between two dots if those two are friends. Dots are called vertices and lines are called edges. That is a graph!
How it works, step by step
- Decide what a vertex is. A person, a city, a page, a task. Give each one a name or number.
- Decide what an edge means. "Is friends with", "has a road to", "links to". An edge always joins two vertices.
- Store the vertices (a list of names) and the edges (a list of pairs).
- Neighbours of a vertex are the vertices it shares an edge with. Almost every graph question starts by asking for them.
The code in four languages
PHP
<?php
// The simplest graph: a list of vertices and a list of edges (pairs).
$vertices = ['A', 'B', 'C', 'D', 'E', 'F'];
$edges = [['A','B'], ['B','C'], ['A','D'], ['B','E'], ['D','E'], ['E','F'], ['C','F']];
// Neighbours of a vertex: every edge that touches it, take the OTHER end.
function neighbours(array $edges, string $v): array {
$out = [];
foreach ($edges as [$a, $b]) {
if ($a === $v) $out[] = $b;
elseif ($b === $v) $out[] = $a;
}
return $out;
}
echo 'Vertices: ' . count($vertices) . "\n";
echo 'Edges: ' . count($edges) . "\n";
echo 'Neighbours of B: ' . implode(', ', neighbours($edges, 'B')) . "\n";JavaScript
// The simplest graph: a list of vertices and a list of edges (pairs).
const vertices = ['A', 'B', 'C', 'D', 'E', 'F'];
const edges = [['A','B'], ['B','C'], ['A','D'], ['B','E'], ['D','E'], ['E','F'], ['C','F']];
// Neighbours of a vertex: every edge that touches it, take the OTHER end.
function neighbours(edges, v) {
const out = [];
for (const [a, b] of edges) {
if (a === v) out.push(b);
else if (b === v) out.push(a);
}
return out;
}
console.log('Vertices: ' + vertices.length);
console.log('Edges: ' + edges.length);
console.log('Neighbours of B: ' + neighbours(edges, 'B').join(', '));Java
import java.util.*;
public class Main {
// Neighbours of a vertex: every edge that touches it, take the OTHER end.
static List<String> neighbours(List<String[]> edges, String v) {
List<String> out = new ArrayList<>();
for (String[] e : edges) {
if (e[0].equals(v)) out.add(e[1]);
else if (e[1].equals(v)) out.add(e[0]);
}
return out;
}
public static void main(String[] args) {
// The simplest graph: a list of vertices and a list of edges (pairs).
List<String> vertices = List.of("A", "B", "C", "D", "E", "F");
List<String[]> edges = List.of(
new String[]{"A", "B"}, new String[]{"B", "C"}, new String[]{"A", "D"},
new String[]{"B", "E"}, new String[]{"D", "E"}, new String[]{"E", "F"},
new String[]{"C", "F"});
// Count the dots and the lines, then ask who is next to B
System.out.println("Vertices: " + vertices.size());
System.out.println("Edges: " + edges.size());
System.out.println("Neighbours of B: " + String.join(", ", neighbours(edges, "B")));
}
}Go
package main
import (
"fmt"
"strings"
)
// An edge is a pair of vertices.
type Edge struct{ a, b string }
// neighbours finds every edge that touches v and takes the OTHER end.
func neighbours(edges []Edge, v string) []string {
var out []string
for _, e := range edges {
if e.a == v {
out = append(out, e.b)
} else if e.b == v {
out = append(out, e.a)
}
}
return out
}
func main() {
// The simplest graph: a list of vertices and a list of edges (pairs).
vertices := []string{"A", "B", "C", "D", "E", "F"}
edges := []Edge{{"A", "B"}, {"B", "C"}, {"A", "D"}, {"B", "E"}, {"D", "E"}, {"E", "F"}, {"C", "F"}}
// Count the dots and the lines, then ask who is next to B
fmt.Println("Vertices:", len(vertices))
fmt.Println("Edges:", len(edges))
fmt.Println("Neighbours of B: " + strings.Join(neighbours(edges, "B"), ", "))
}Time: O(E) to list neighbours from a plain pair list · Extra space: O(V + E). Storing a graph costs one slot per vertex and one per edge. Faster layouts (matrix, list) come in the next lessons.
Watch out for
- Thinking an edge can join three or more things. An edge always joins exactly two vertices.
- Counting a friendship twice (A-B and B-A) in an undirected graph. It is one edge.
- Drawing everything. A graph keeps only the facts that matter for the question.
Quick check
- In a road map graph, what is a vertex?
- A junction or place
- A road
- The map itself
- How many vertices can one edge join?
- One
- Exactly two
- As many as needed
- Two vertices share an edge. What are they called?
- Roots
- Leaves
- Neighbours