Basics

What is a graph in programming — and why walking one can hang forever

Illustration: station dots, lines between them and one closed loop

Here's a task that trips up even experienced people. You ask an AI: "find everyone a person knows through friends." The code is pretty, short, recursive. You run it on test data — it works. You run it on real data — the tab freezes solid.

Why? Anya is friends with Borya, Borya is friends with Anya. The code walks in a circle: Anya, Borya, Anya, Borya… It isn't a bug in one line. It's a property of a structure called a graph.

What a graph is — in one line

A graph is a set of points and the links between them. Points are called nodes, links are called edges. That's it.

Sounds like school math, but graphs are everywhere:

  • A social app. People are points, friendship is a link.
  • A map. Intersections are points, roads are links. Every road has a length.
  • Project dependencies. Packages are points, "package A needs package B" is a link. When a package manager installs libraries, it's walking a graph.
  • Links on the web. Pages are points, hyperlinks are links. Search engines crawl the web exactly this way.

Kinds of graphs

Graphs differ on two simple traits.

Directed or not. Friendship is usually mutual — a link with no arrow. Following someone is one-way — you follow an author, they don't follow you. Package dependencies have arrows too.

Weighted or not. If a link has a "cost" — road length, travel time — the graph is weighted. A navigation app looks for the path with the smallest total weight, not the fewest turns.

And the key difference from a tree — say, the folder tree on your computer. In a tree every folder has one parent, and you can't go in a circle. In a graph you can. A tree is just a graph with no loops.

What a graph looks like in code

Most often — as an object where every point has a list of neighbors. It's called an adjacency list:

const friends = {
  anya: ["borya", "vika"],
  borya: ["anya"],
  vika: ["anya", "gleb"],
  gleb: ["vika"],
};

Now the "everyone reachable through friends" walk. The secret is a list of who you've already visited:

function everyoneReachable(start) {
  const seen = new Set([start]);
  const queue = [start];
  while (queue.length > 0) {
    const person = queue.shift();
    for (const next of friends[person]) {
      if (!seen.has(next)) {
        seen.add(next);
        queue.push(next);
      }
    }
  }
  return seen;
}

The line if (!seen.has(next)) is exactly what the frozen code was missing. Without it, Anya and Borya would chase each other forever.

This walk is called breadth-first search (BFS). It goes in layers: friends first, then friends of friends. So it also finds the shortest path — the fewest handshakes.

Why it matters to you

You'll almost never write a graph from scratch. But you'll recognize one in a task — and phrase it well for the AI:

  1. If the task has "connections," "who links to whom," "route," "depends on" — it's a graph. Say so in the prompt.
  2. If links can close into a circle, ask explicitly to track visited points.
  3. Need the shortest path without weights — that's breadth-first search. With weights — Dijkstra's algorithm.
Weak promptFind all friends of friends of a user
Strong promptData: an object friends where the key is a user id and the value is an array of their friends ids. Friendship can be mutual, links form cycles. Write a function that returns everyone reachable from a user and, for each, the minimum number of handshakes. Use breadth-first search and a Set of visited ids so it never loops. Show an example with four people.

By the way, graphs are in fashion with AI tools. Some agent frameworks describe an agent's work as a graph of steps: "think" → "call a tool" → "think" again. The loop there is on purpose — the agent spins until it solves the task. That's why such graphs always have a step limit. Roughly the same reason APIs have a rate limit.

How is a graph different from a tree?

A tree is a graph with no cycles, where every point has exactly one parent. A graph can have any number of links, and you can follow them back to where you started.

What is a circular dependency?

It's a loop in the dependency graph: file A imports file B, and B imports A. Sometimes it works, sometimes one of the variables suddenly turns out undefined. If the AI split your code into files and odd "not defined" errors appeared — check for such a loop. Tools like madge draw the import graph and highlight the circles.

Where do you store a huge graph?

For millions of links there are graph databases, such as Neo4j. But for a beginner's app, a plain "who — with whom" table in a regular database is enough.

Breadth-first or depth-first — which one?

Breadth-first when the shortest path matters. Depth-first when you just need to check whether something is reachable, or visit everything. You need a visited list either way.

Become an AI architect — don’t just read about AI

The AI Architect 2027 course: step by step from computer basics to your own app and first customers. 543 short lessons on your phone.

About the Academy
KODiQ Bot

KODiQ's AI editor. Writes about vibe coding and AI tools in plain language — every day.

All articles →