What a graph is
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A graph is a versatile non-linear data structure that models arbitrary relationships between interconnected entities.
Vertices, edges, and graph terminology
A graph is a set of nodes (vertices) connected by edges. Edges can be directed or undirected, and weighted or unweighted.
A graph is a set of vertices connected by a set of edges. It models networks with loops and many connections, which arrays, lists and trees cannot.
String[] cities = {"Delhi", "Mumbai", "Pune", "Chennai"}; // vertices Vint[][] roads = {{0, 1}, {1, 2}, {2, 0}, {2, 3}}; // edges E// degree of Pune (2) = 3: roads to Mumbai, Delhi and Chennai// path: Delhi -> Mumbai -> Pune -> Chennai// cycle: Delhi -> Mumbai -> Pune -> DelhiVertices are entities such as cities, servers or people. Edges are the relationships between pairs of them.
The degree of a vertex is the number of edges at it. A path is a sequence of vertices joined by edges, a cycle is a path that returns to its start, and a graph is connected if a path joins every pair of vertices.
Predict the output
Predict the degree
Edges are pairs of vertices. Pick what each snippet prints.
Round 1 of 2
Directed, undirected, and weighted graphs
Graphs are classified based on the nature and direction of their edges. In an undirected graph, edges are bidirectional two-way connections. An edge between vertices u and v allows moving both u to v and v to u freely.
Example 1 · Computing Vertex Degrees in Undirected Graphs
public class Main { static int getDegree(int[][] edges, int n, int vertex) { int degree = 0; for (int[] edge : edges) { if (edge[0] == vertex || edge[1] == vertex) { degree++; } } return degree; }
public static void main(String[] args) { int[][] edges = {{0, 1}, {0, 2}, {1, 2}, {2, 3}}; System.out.println("Degree of vertex 0: " + getDegree(edges, 4, 0)); System.out.println("Degree of vertex 2: " + getDegree(edges, 4, 2)); }}Degree of vertex 0: 2 Degree of vertex 2: 3
What this code does
- Vertex 0 connects to vertices 1 and 2, giving degree 2.
- Vertex 2 connects to vertices 0, 1, and 3, giving degree 3.
- In undirected graphs, each connected edge increments vertex degree.
Example 2 · Computing In-Degree and Out-Degree in Directed Graphs
public class Main { public static void main(String[] args) { int n = 4; int[][] directedEdges = {{0, 1}, {0, 2}, {1, 2}, {2, 0}, {3, 2}}; int[] inDegree = new int[n]; int[] outDegree = new int[n];
for (int[] edge : directedEdges) { int u = edge[0]; int v = edge[1]; outDegree[u]++; inDegree[v]++; }
for (int i = 0; i < n; i++) { System.out.println("Vertex " + i + ": in=" + inDegree[i] + ", out=" + outDegree[i]); } }}Vertex 0: in=1, out=2 Vertex 1: in=1, out=1 Vertex 2: in=3, out=1 Vertex 3: in=0, out=1
What this code does
- Out-degree counts outgoing edges leaving the vertex.
- In-degree counts incoming edges pointing into the vertex.
- Vertex 2 has three incoming edges: from 0, 1, and 3.
Example 3 · Calculating Path Cost in a Weighted Graph
import java.util.*;
public class Main { static class Edge { int to, weight; Edge(int to, int weight) { this.to = to; this.weight = weight; } }
public static void main(String[] args) { Map<String, Integer> weights = new HashMap<>(); weights.put("A-B", 5); weights.put("B-C", 10); weights.put("C-D", 3);
String[] path = {"A", "B", "C", "D"}; int totalCost = 0; for (int i = 0; i < path.length - 1; i++) { String key = path[i] + "-" + path[i + 1]; totalCost += weights.get(key); } System.out.println("Total path cost: " + totalCost + " km"); }}Total path cost: 18 km
What this code does
- Each step along the path retrieves its corresponding edge weight.
- Weights accumulate: 5 + 10 + 3 = 18.
- Weighted graphs allow evaluating the cost of alternate travel routes.
In a directed graph or digraph, edges have a defined one-way orientation from source to destination. A directed edge from u to v allows moving u to v, but not the reverse. In directed graphs, in-degree counts incoming edges while out-degree counts outgoing edges. In a weighted graph, each edge carries a numerical weight or cost value. Weights represent real quantities such as physical distance, travel time, or bandwidth capacity.
Modeling real world problems as graphs
GPS mapping systems represent road networks as weighted graphs. Street intersections become vertices, and road segments become edges weighted by drive times. Shortest path algorithms calculate the fastest driving route across this graph representation.
Software build systems model package dependencies as directed graphs. Packages are vertices, and dependency imports form directed edges between them. Detecting cycles in this dependency graph catches circular import errors before compilation.
Social networks model accounts as vertices, using undirected edges for mutual friendships and directed edges for follower links.
Next step
Check your understanding
10 quick questions