πŸ•ΈοΈ PHP Graph Basics

Graph Representations

Adjacency List (Most Common)

// Undirected graph
$graph = [
    0 => [1, 2],
    1 => [0, 3],
    2 => [0, 4],
    3 => [1],
    4 => [2],
];

// Directed graph (0β†’1, 1β†’2, 2β†’3)
$directed = [
    0 => [1],
    1 => [2],
    2 => [3],
    3 => [],
];

Adjacency Matrix

// nΓ—n matrix; matrix[i][j] = 1 means edge from i to j
$n = 4;
$matrix = array_fill(0, $n, array_fill(0, $n, 0));
$matrix[0][1] = 1; // 0β†’1
$matrix[1][2] = 1; // 1β†’2

Adjacency list: O(V + E) space β€” preferred for sparse graphs. Adjacency matrix: O(VΒ²) space β€” preferred for dense graphs or O(1) edge lookup.


Build Graph from Edge List

function buildGraph(int $n, array $edges): array {
    $graph = array_fill(0, $n, []);
    foreach ($edges as [$u, $v]) {
        $graph[$u][] = $v;
        $graph[$v][] = $u; // remove for directed
    }
    return $graph;
}

$graph = buildGraph(5, [[0,1],[0,2],[1,3],[2,4]]);

Graph Terminology

TermMeaning
Vertex / NodeA point in the graph
EdgeA connection between two vertices
DegreeNumber of edges on a vertex
PathSequence of vertices connected by edges
CycleA path that returns to the start
DAGDirected Acyclic Graph
ConnectedEvery vertex reachable from every other
ComponentA maximal connected subgraph

Union-Find (Disjoint Set Union)

Essential for connected components and cycle detection.

class UnionFind {
    private array $parent;
    private array $rank;

    public function __construct(int $n) {
        $this->parent = range(0, $n - 1);
        $this->rank   = array_fill(0, $n, 0);
    }

    public function find(int $x): int {
        if ($this->parent[$x] !== $x)
            $this->parent[$x] = $this->find($this->parent[$x]); // path compression
        return $this->parent[$x];
    }

    public function union(int $x, int $y): bool {
        $px = $this->find($x);
        $py = $this->find($y);
        if ($px === $py) return false; // already connected
        if ($this->rank[$px] < $this->rank[$py]) [$px, $py] = [$py, $px];
        $this->parent[$py] = $px;
        if ($this->rank[$px] === $this->rank[$py]) $this->rank[$px]++;
        return true;
    }

    public function connected(int $x, int $y): bool {
        return $this->find($x) === $this->find($y);
    }
}

Time: O(Ξ±(n)) β‰ˆ O(1) per operation | Space: O(n)


Complexity Summary

RepresentationSpaceEdge LookupAdd Edge
Adjacency ListO(V+E)O(degree)O(1)
Adjacency MatrixO(VΒ²)O(1)O(1)
AlgorithmTimeSpace
BFSO(V + E)O(V)
DFSO(V + E)O(V)
Topological SortO(V + E)O(V)
Union-FindO(Ξ±(n)) per opO(V)