Skip to content

Graph

In one line

A graph is a data structure of nodes (vertices) connected by edges, modeling relationships between entities.

In simple words

A graph is a set of vertices (nodes) connected by edges (links). Unlike a tree, a graph has no single root and nodes can have multiple connections, cycles, and even edges that point back to the same node. Graphs model any network of relationships: social networks, road maps, the web (pages linking to pages), and dependencies between modules.

Graphs can be directed (edges have a direction, like one-way streets) or undirected (edges go both ways). They can be weighted (edges have a cost, like distances) or unweighted. Two common representations are the adjacency list (each node stores a list of its neighbors) and the adjacency matrix (a 2D grid of 0/1 or weights).

Key graph algorithms include breadth-first search (shortest path in unweighted graphs), depth-first search (exploring as far as possible before backtracking), Dijkstra's algorithm (shortest weighted path), and topological sort (ordering tasks with dependencies).

Example

javascript
// Adjacency list representation
const graph = {
  A: ["B", "C"],
  B: ["A", "D"],
  C: ["A", "D"],
  D: ["B", "C"],
};

// BFS — visit all nodes reachable from start
function bfs(graph, start) {
  const visited = new Set([start]);
  const queue = [start];
  const order = [];
  while (queue.length) {
    const node = queue.shift();
    order.push(node);
    graph[node].forEach(n => {
      if (!visited.has(n)) { visited.add(n); queue.push(n); }
    });
  }
  return order;
}
console.log(bfs(graph, "A")); // ["A", "B", "C", "D"]

The graph is stored as an adjacency list. BFS uses a queue to visit neighbors level by level, tracking visited nodes to avoid cycles.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary