AlgoTales · Roadmap

Connected/disconnected graphs

Beginner · 7 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A graph is connected when you can get from any dot to any other by following lines, and disconnected when some groups are cut off from the rest. Knowing which parts are islands tells you what is unreachable, isolated or broken.

Practical use cases

  • Web app: Is the delivery area fully reachable?. A food-delivery app defines delivery zones as areas joined by roads. Before launching a new zone, the team checks that all addresses are connected to the kitchen. The check finds two housing blocks cut off by a river with no bridge in the data, so orders there will not fail later. The team fixes the map data before launch day.
  • Web app: Finding separate friend groups. A social platform wants to know how many separate communities exist and whether a new user has joined one. Counting connected groups answers both. Users who are not connected to anyone show up immediately as isolated accounts. The team can then send those users a gentle invite to connect.
  • System: Network reliability and level design. Network engineers check that no part of the network gets cut off if one cable fails. Game designers check that a player can reach every room of a level and not get stuck behind a wall. Both checks run automatically before release.

The story: The Two Islands of the Monsoon

After the monsoon, a river changed its path and Mira's district was cut in two. Villages A, B and C could still visit each other on the old roads. Villages D, E and F could too. But nobody on one side could reach the other side at all.

The district officer asked a simple question: "Can a person from any village reach any other village?" Mira did not check every pair. She stood at village A and spread the news like gossip, village to village, following only roads.

When the spreading stopped, only three villages had heard it. "Not everyone is reachable," she reported. A bridge was built from B to D. She repeated the test and this time all six villages were reached.

A graph where every vertex can reach every other is connected. If the test leaves some behind, the graph is disconnected, made of separate islands.

How to spot this problem, and where you need it

You need to know whether everything can reach everything else, and if not, which pieces are cut off or how many separate groups there are.

Signs you need it

  • Users report "no route found", or an order is rejected for an address that looks valid on the map.
  • You want to count separate groups: communities, clusters, islands or networks.
  • The task says "is the graph connected", "number of components", or "can every node be reached".

Where to use it in a project

  • Validating map, route or delivery-zone data before a launch.
  • Spotting isolated users, orphan pages or separate clusters in social, link or dependency data.

The solution

Pick any dot and spread out from it, visiting every dot you can reach (a level-by-level or depth-first search). Mark each as visited. If every dot got marked, the graph is connected. If some are left, pick one of them, start another spread, and count it as a new group. The number of spreads equals the number of separate groups.

Payoff: Before: orders to two unreachable blocks fail after launch. After: a pre-launch check lists exactly which areas are disconnected.

Explain it like I am 8

Imagine a set of toy islands joined by bridges. If you can walk from any island to any other island, the toy world is connected. If some islands are cut off and you cannot walk there, it is disconnected.

How it works, step by step

  1. Pick any start vertex. Any one will do, if the graph is connected, all start points give the same answer.
  2. Walk everywhere you can using BFS or DFS, marking each vertex visited.
  3. Count the visited vertices.
  4. If the count equals the total number of vertices, the graph is connected. Otherwise it is disconnected.

The code in four languages

PHP

<?php
// Is every vertex reachable from the first one?
function isConnected(array $graph): bool {
    $nodes = array_keys($graph);
    if (count($nodes) === 0) return true;
    $seen = [$nodes[0] => true];
    $stack = [$nodes[0]];
    while ($stack) {
        $node = array_pop($stack);
        foreach ($graph[$node] as $next) {
            if (!isset($seen[$next])) {
                $seen[$next] = true;       // mark when discovered
                $stack[] = $next;
            }
        }
    }
    return count($seen) === count($nodes);  // reached everybody?
}

$twoIslands = ['A'=>['B','C'], 'B'=>['A','C'], 'C'=>['A','B'], 'D'=>['E'], 'E'=>['D','F'], 'F'=>['E']];
$bridged = $twoIslands;
$bridged['B'][] = 'D';
$bridged['D'][] = 'B';

echo 'Two islands connected? ' . (isConnected($twoIslands) ? 'yes' : 'no') . "\n";
echo 'With the bridge connected? ' . (isConnected($bridged) ? 'yes' : 'no') . "\n";

JavaScript

// Is every vertex reachable from the first one?
function isConnected(graph) {
  const nodes = Object.keys(graph);
  if (nodes.length === 0) return true;
  const seen = new Set([nodes[0]]);
  const stack = [nodes[0]];
  while (stack.length) {
    const node = stack.pop();
    for (const next of graph[node]) {
      if (!seen.has(next)) {
        seen.add(next);                    // mark when discovered
        stack.push(next);
      }
    }
  }
  return seen.size === nodes.length;       // reached everybody?
}

const twoIslands = { A: ['B','C'], B: ['A','C'], C: ['A','B'], D: ['E'], E: ['D','F'], F: ['E'] };
const bridged = { ...twoIslands, B: ['A','C','D'], D: ['E','B'] };

console.log('Two islands connected? ' + (isConnected(twoIslands) ? 'yes' : 'no'));
console.log('With the bridge connected? ' + (isConnected(bridged) ? 'yes' : 'no'));

Java

import java.util.*;

public class Main {
    // Is every vertex reachable from the first one?
    static boolean isConnected(Map<String, List<String>> graph) {
        if (graph.isEmpty()) return true;
        String start = graph.keySet().iterator().next();
        Set<String> seen = new HashSet<>(List.of(start));
        Deque<String> stack = new ArrayDeque<>(List.of(start));
        while (!stack.isEmpty()) {
            String node = stack.pop();
            for (String next : graph.get(node)) {
                if (seen.add(next)) {              // mark when discovered
                    stack.push(next);
                }
            }
        }
        return seen.size() == graph.size();        // reached everybody?
    }

    public static void main(String[] args) {
        Map<String, List<String>> twoIslands = new LinkedHashMap<>();
        twoIslands.put("A", List.of("B", "C"));
        twoIslands.put("B", List.of("A", "C"));
        twoIslands.put("C", List.of("A", "B"));
        twoIslands.put("D", List.of("E"));
        twoIslands.put("E", List.of("D", "F"));
        twoIslands.put("F", List.of("E"));

        Map<String, List<String>> bridged = new LinkedHashMap<>(twoIslands);
        bridged.put("B", List.of("A", "C", "D"));  // the bridge B - D
        bridged.put("D", List.of("E", "B"));

        System.out.println("Two islands connected? " + (isConnected(twoIslands) ? "yes" : "no"));
        System.out.println("With the bridge connected? " + (isConnected(bridged) ? "yes" : "no"));
    }
}

Go

package main

import "fmt"

// isConnected reports whether every vertex is reachable from an arbitrary first one.
func isConnected(graph map[string][]string) bool {
	if len(graph) == 0 {
		return true
	}
	var start string
	for node := range graph { // any vertex will do as the starting point
		start = node
		break
	}
	seen := map[string]bool{start: true}
	stack := []string{start}
	for len(stack) > 0 {
		node := stack[len(stack)-1]
		stack = stack[:len(stack)-1]
		for _, next := range graph[node] {
			if !seen[next] {
				seen[next] = true // mark when discovered
				stack = append(stack, next)
			}
		}
	}
	return len(seen) == len(graph) // reached everybody?
}

func yesNo(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

func main() {
	twoIslands := map[string][]string{
		"A": {"B", "C"}, "B": {"A", "C"}, "C": {"A", "B"},
		"D": {"E"}, "E": {"D", "F"}, "F": {"E"},
	}
	bridged := map[string][]string{}
	for k, v := range twoIslands {
		bridged[k] = v
	}
	bridged["B"] = []string{"A", "C", "D"} // the bridge B - D
	bridged["D"] = []string{"E", "B"}

	fmt.Println("Two islands connected?", yesNo(isConnected(twoIslands)))
	fmt.Println("With the bridge connected?", yesNo(isConnected(bridged)))
}

Time: O(V + E) · Extra space: O(V). One walk that touches each vertex and each edge about once is enough to decide.

Watch out for

  • Checking only whether the start vertex has neighbours. A big island can still hide another island.
  • For directed graphs, mixing up "connected" with "strongly connected" (can reach each other following arrows). Part 2 covers that.
  • Forgetting isolated vertices with no edges at all. They make the graph disconnected.

Quick check

  1. A walk from A visits 3 of 6 vertices. The graph is…
    • Disconnected
    • Connected
    • Weighted
  2. Which single change can turn a two-piece graph into a connected one?
    • Delete a vertex
    • Add one edge between the two pieces
    • Add an edge inside one piece
  3. How many start vertices must you try to test connectedness?
    • Every vertex
    • Half of them
    • Just one