AlgoTales · Roadmap

Euler path/circuit

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

An Euler path travels along every link exactly once, and an Euler circuit does so and returns to the start. A simple counting rule on how many links each place has tells you instantly whether such a tour exists.

Practical use cases

  • Web app: Street-sweeping or garbage route planner. A city app plans a route where a truck must pass every street once. Before computing anything, it checks how many streets meet at each junction; if at most two junctions have an odd number, the route exists. Otherwise it tells the planner which streets need to be repeated.
  • Web app: Postal or courier daily round. A courier app has streets with parcels on both sides. Finding a walk covering every street once saves doubling back, and the check is a quick count rather than trial and error.
  • Web app: Pen-plotter or SVG drawing export. A tool that exports drawings to a plotter wants to draw all lines without lifting the pen. It counts line ends at each point and builds a single continuous stroke where possible, saving machine time.
  • System: DNA assembly and puzzles. Genome assemblers join short pieces by finding a walk that uses each piece exactly once, and classic bridge-crossing puzzles use the same rule. In each case the first step is the same quick count of lines at each point, and only then is a route built, so nothing is wasted on hopeless searches.

The story: Raju the Postman's Perfect Round

Raju's cousin was a postman and he hated retracing his steps. "I want a round where I walk every lane in the mohalla exactly once and return to the post office," he said. Some days he found one; other days he gave up after hours of trying.

Mira noticed a pattern. Every time you walk into a junction you need a different lane to walk out. So at junctions in the middle of the walk, the lanes come in pairs: one in, one out. A junction with an odd number of lanes would leave you stuck with a spare lane.

"So if every junction has an even number of lanes, a full round is possible, and you end where you started," she announced. "If exactly two junctions are odd, you can still walk every lane once, but you must start at one odd junction and finish at the other. With any other number of odd junctions, forget it."

This is exactly the 18th-century puzzle of the bridges of Königsberg that Leonhard Euler solved. A walk using every edge once is an Euler path; if it returns to the start it is an Euler circuit. Counting the degrees decides the answer in a flash, as long as all the lanes are in one connected piece.

How to spot this problem, and where you need it

You must cover every link, road, line or connection exactly once in one continuous trip, and want to know if that is possible before wasting time searching.

Signs you need it

  • The task says "use every road exactly once", "draw without lifting the pen", or "each edge once".
  • You are trying every route by brute force and it explodes with more streets.
  • Each junction has a number of links that you can count quickly.

Where to use it in a project

  • Route planning for sweepers, meter readers, snow ploughs and postmen covering every street.
  • Export tools for plotters, laser cutters or 3D printers that want minimal pen lifts.

The solution

Count the number of links at each node. If all are even and the network is connected, an Euler circuit exists; if exactly two are odd, an Euler path exists starting at one odd node and ending at the other; otherwise it is impossible. To build the route, use Hierholzer: walk along unused links until stuck, then splice in extra loops from earlier nodes that still have unused links.

Payoff: Before: trying thousands of routes by trial. After: a quick count answers yes or no, and the route is built in one pass.

Explain it like I am 8

Try to draw a picture without lifting your pencil and without drawing any line twice. It works if all the dots have an even number of lines, or if exactly two dots are odd (start at one, end at the other).

How it works, step by step

  1. Check connectivity: all lanes must belong to one connected piece (ignore junctions with no lanes).
  2. Count the degree of every junction (how many lanes touch it).
  3. If all degrees are even: an Euler circuit exists. Start anywhere.
  4. If exactly two degrees are odd: an Euler path exists. Start at one odd junction.
  5. Any other count of odd junctions: impossible. To actually build the walk, use Hierholzer's algorithm (walk until stuck, then splice in the loops you skipped).

The code in four languages

PHP

<?php
// Euler path/circuit with Hierholzer's algorithm. Returns the walk, or null if impossible.
function eulerWalk(int $n, array $lanes): ?array {
    $adj = array_fill(0, $n, []);
    foreach ($lanes as $id => [$a, $b]) {
        $adj[$a][] = [$b, $id];
        $adj[$b][] = [$a, $id];
    }
    $odd = [];
    for ($i = 0; $i < $n; $i++) {
        if (count($adj[$i]) % 2 === 1) $odd[] = $i;      // degree is odd
    }
    if (count($odd) !== 0 && count($odd) !== 2) return null;   // the degree rule

    $start = $odd ? $odd[0] : $lanes[0][0];              // an odd junction, else any
    $used = array_fill(0, count($lanes), false);
    $next = array_fill(0, $n, 0);                        // next unused lane to try per junction
    $stack = [$start];
    $walk = [];
    while ($stack) {
        $u = $stack[count($stack) - 1];
        while ($next[$u] < count($adj[$u]) && $used[$adj[$u][$next[$u]][1]]) $next[$u]++;
        if ($next[$u] === count($adj[$u])) {
            $walk[] = array_pop($stack);                 // stuck: this junction is done
        } else {
            [$v, $id] = $adj[$u][$next[$u]];
            $used[$id] = true;                           // cross the lane off
            $stack[] = $v;
        }
    }
    // If some lanes are unreachable (disconnected map) the walk is too short
    return count($walk) === count($lanes) + 1 ? array_reverse($walk) : null;
}

// the envelope map: P=0 Q=1 R=2 S=3 T=4
$envelope = [[0,1],[0,2],[1,3],[2,3],[2,4],[3,4],[0,3],[1,2]];
echo 'Envelope: ' . implode(' ', eulerWalk(5, $envelope) ?? ['none']) . PHP_EOL;
// bow-tie map (all even): A=0 B=1 C=2 D=3 F=4
$bow = [[0,1],[0,2],[1,2],[2,3],[2,4],[3,4]];
echo 'Bow-tie: ' . implode(' ', eulerWalk(5, $bow) ?? ['none']) . PHP_EOL;
// four odd junctions: impossible
$k4 = [[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]];
echo 'Four odd: ' . implode(' ', eulerWalk(4, $k4) ?? ['none']) . PHP_EOL;

JavaScript

// Euler path/circuit with Hierholzer's algorithm. Returns the walk, or null if impossible.
function eulerWalk(n, lanes) {
  const adj = Array.from({ length: n }, () => []);
  lanes.forEach(([a, b], id) => {
    adj[a].push([b, id]);
    adj[b].push([a, id]);
  });
  const odd = [];
  for (let i = 0; i < n; i++) {
    if (adj[i].length % 2 === 1) odd.push(i);              // degree is odd
  }
  if (odd.length !== 0 && odd.length !== 2) return null;   // the degree rule

  const start = odd.length ? odd[0] : lanes[0][0];         // an odd junction, else any
  const used = new Array(lanes.length).fill(false);
  const next = new Array(n).fill(0);                       // next unused lane to try per junction
  const stack = [start];
  const walk = [];
  while (stack.length) {
    const u = stack[stack.length - 1];
    while (next[u] < adj[u].length && used[adj[u][next[u]][1]]) next[u]++;
    if (next[u] === adj[u].length) {
      walk.push(stack.pop());                              // stuck: this junction is done
    } else {
      const [v, id] = adj[u][next[u]];
      used[id] = true;                                     // cross the lane off
      stack.push(v);
    }
  }
  // If some lanes are unreachable (disconnected map) the walk is too short
  return walk.length === lanes.length + 1 ? walk.reverse() : null;
}

// the envelope map: P=0 Q=1 R=2 S=3 T=4
const envelope = [[0,1],[0,2],[1,3],[2,3],[2,4],[3,4],[0,3],[1,2]];
console.log('Envelope: ' + (eulerWalk(5, envelope) || ['none']).join(' '));
// bow-tie map (all even): A=0 B=1 C=2 D=3 F=4
const bow = [[0,1],[0,2],[1,2],[2,3],[2,4],[3,4]];
console.log('Bow-tie: ' + (eulerWalk(5, bow) || ['none']).join(' '));
// four odd junctions: impossible
const k4 = [[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]];
console.log('Four odd: ' + (eulerWalk(4, k4) || ['none']).join(' '));

Java

import java.util.*;

public class Main {
    // Euler path/circuit with Hierholzer's algorithm. Returns the walk, or null if impossible.
    static List<Integer> eulerWalk(int n, int[][] lanes) {
        List<List<int[]>> adj = new ArrayList<>();            // each entry: {neighbour, lane id}
        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
        for (int id = 0; id < lanes.length; id++) {
            adj.get(lanes[id][0]).add(new int[]{lanes[id][1], id});
            adj.get(lanes[id][1]).add(new int[]{lanes[id][0], id});
        }
        List<Integer> odd = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            if (adj.get(i).size() % 2 == 1) odd.add(i);       // degree is odd
        }
        if (odd.size() != 0 && odd.size() != 2) return null;  // the degree rule

        int start = odd.isEmpty() ? lanes[0][0] : odd.get(0); // an odd junction, else any
        boolean[] used = new boolean[lanes.length];
        int[] next = new int[n];                              // next unused lane to try per junction
        Deque<Integer> stack = new ArrayDeque<>();
        stack.push(start);
        List<Integer> walk = new ArrayList<>();
        while (!stack.isEmpty()) {
            int u = stack.peek();
            while (next[u] < adj.get(u).size() && used[adj.get(u).get(next[u])[1]]) next[u]++;
            if (next[u] == adj.get(u).size()) {
                walk.add(stack.pop());                        // stuck: this junction is done
            } else {
                int[] lane = adj.get(u).get(next[u]);
                used[lane[1]] = true;                         // cross the lane off
                stack.push(lane[0]);
            }
        }
        // If some lanes are unreachable (disconnected map) the walk is too short
        if (walk.size() != lanes.length + 1) return null;
        Collections.reverse(walk);
        return walk;
    }

    static String show(List<Integer> walk) {
        if (walk == null) return "none";
        StringBuilder sb = new StringBuilder();
        for (int x : walk) sb.append(sb.length() == 0 ? "" : " ").append(x);
        return sb.toString();
    }

    public static void main(String[] args) {
        // the envelope map: P=0 Q=1 R=2 S=3 T=4
        int[][] envelope = {{0, 1}, {0, 2}, {1, 3}, {2, 3}, {2, 4}, {3, 4}, {0, 3}, {1, 2}};
        System.out.println("Envelope: " + show(eulerWalk(5, envelope)));
        // bow-tie map (all even): A=0 B=1 C=2 D=3 F=4
        int[][] bow = {{0, 1}, {0, 2}, {1, 2}, {2, 3}, {2, 4}, {3, 4}};
        System.out.println("Bow-tie: " + show(eulerWalk(5, bow)));
        // four odd junctions: impossible
        int[][] k4 = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}};
        System.out.println("Four odd: " + show(eulerWalk(4, k4)));
    }
}

Go

package main

import (
	"fmt"
	"strconv"
	"strings"
)

type lane struct{ to, id int }

// eulerWalk uses Hierholzer's algorithm. It returns the walk, or ok=false if impossible.
func eulerWalk(n int, lanes [][2]int) (walk []int, ok bool) {
	adj := make([][]lane, n)
	for id, l := range lanes {
		adj[l[0]] = append(adj[l[0]], lane{l[1], id})
		adj[l[1]] = append(adj[l[1]], lane{l[0], id})
	}
	var odd []int
	for i := 0; i < n; i++ {
		if len(adj[i])%2 == 1 {
			odd = append(odd, i) // degree is odd
		}
	}
	if len(odd) != 0 && len(odd) != 2 {
		return nil, false // the degree rule
	}

	start := lanes[0][0] // any junction...
	if len(odd) > 0 {
		start = odd[0] // ...unless there is an odd one
	}
	used := make([]bool, len(lanes))
	next := make([]int, n) // next unused lane to try per junction
	stack := []int{start}
	for len(stack) > 0 {
		u := stack[len(stack)-1]
		for next[u] < len(adj[u]) && used[adj[u][next[u]].id] {
			next[u]++
		}
		if next[u] == len(adj[u]) {
			walk = append(walk, u) // stuck: this junction is done
			stack = stack[:len(stack)-1]
		} else {
			l := adj[u][next[u]]
			used[l.id] = true // cross the lane off
			stack = append(stack, l.to)
		}
	}
	// If some lanes are unreachable (disconnected map) the walk is too short
	if len(walk) != len(lanes)+1 {
		return nil, false
	}
	for i, j := 0, len(walk)-1; i < j; i, j = i+1, j-1 {
		walk[i], walk[j] = walk[j], walk[i] // reverse
	}
	return walk, true
}

func show(walk []int, ok bool) string {
	if !ok {
		return "none"
	}
	words := make([]string, len(walk))
	for i, x := range walk {
		words[i] = strconv.Itoa(x)
	}
	return strings.Join(words, " ")
}

func main() {
	// the envelope map: P=0 Q=1 R=2 S=3 T=4
	envelope := [][2]int{{0, 1}, {0, 2}, {1, 3}, {2, 3}, {2, 4}, {3, 4}, {0, 3}, {1, 2}}
	fmt.Println("Envelope: " + show(eulerWalk(5, envelope)))
	// bow-tie map (all even): A=0 B=1 C=2 D=3 F=4
	bow := [][2]int{{0, 1}, {0, 2}, {1, 2}, {2, 3}, {2, 4}, {3, 4}}
	fmt.Println("Bow-tie: " + show(eulerWalk(5, bow)))
	// four odd junctions: impossible
	k4 := [][2]int{{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}}
	fmt.Println("Four odd: " + show(eulerWalk(4, k4)))
}

Time: O(V + E) · Extra space: O(V + E). Each lane is crossed off exactly once; the degree check is just counting.

Watch out for

  • Forgetting the connected condition. All even degrees is not enough if the lanes sit in two separate islands.
  • Mixing up Euler (every edge once) with Hamiltonian (every node once). They are very different in difficulty.
  • For a directed graph the rule changes: every node needs in-degree equal to out-degree (circuit), not just even degrees.

Quick check

  1. A connected map has all junctions with an even number of lanes. What exists?
    • An Euler circuit
    • Only an Euler path that ends elsewhere
    • Nothing
  2. A connected map has exactly 2 odd junctions. Where must you start?
    • It is impossible
    • Any junction
    • At one of the two odd junctions
    • At the junction with the most lanes
  3. A map has 4 odd junctions. Is an Euler path possible?
    • Yes, with a lucky guess
    • No
    • Yes, start at any