graph

Directed/undirected weighted graph with BFS, DFS, Dijkstra, toposort and cycles.

v1.0.0Data structuresbundledimport "graph";
Overview Installation Documentation Examples

Overview

Zero-dependency directed and undirected weighted Graph library for HolyPHP with BFS, DFS, Dijkstra shortest path, topological sort, and cycle detection.

bundled — works offline zero dependencies bfs dfs

Quick start

import "graph";

$g = graph_directed();
$g->addEdge("A", "B", 2.0);
$g->addEdge("B", "C", 3.0);
$g->addEdge("A", "C", 10.0);

$res = $g->dijkstra("A", "C");
println("Distance: " . $res["distance"]);        // 5
println("Path: " . implode(" -> ", $res["path"])); // A -> B -> C

$order = $g->toposort();
println("Topo: " . implode(", ", $order));       // A, B, C

Installation

In a project

Inside a project (a folder with hphp.yaml, see Projects & packages):

hphp install graph

This adds the library to hphp.yaml, installs it into .hphp/packages/graph/ and pins the exact version in hphp.lock:

require:
  graph: "^1.0"

Use it

import "graph";

graph is bundled with the compiler, so import "graph"; also works in a single file without installing anything, and hphp install works offline.

Outside a project

hphp install graph          # for your user, shared by all scripts
hphp create myapp                 # or start a project, then: hphp install graph
Packagegraph
Version1.0.0 (follows the compiler)
Entry filegraph.hphp
Sourcepackages/lib/graph ↗

Documentation

API Reference

Factory Functions

class Graph

Constructor

Inspection & Mutation

Traversal & Algorithms

Error Handling

All invalid operations throw Exception with clear, prefixed messages:

Examples

01Quick start

Bundled with the compiler — import "graph"; works offline in any file, or add it to a project with hphp install graph.

import "graph";

$g = graph_directed();
$g->addEdge("A", "B", 2.0);
$g->addEdge("B", "C", 3.0);
$g->addEdge("A", "C", 10.0);

$res = $g->dijkstra("A", "C");
println("Distance: " . $res["distance"]);        // 5
println("Path: " . implode(" -> ", $res["path"])); // A -> B -> C

$order = $g->toposort();
println("Topo: " . implode(", ", $order));       // A, B, C
Try it
hphp install graph
hphp run main.hphp

Covered by the official test suite in tests/positive/lib_graph.hphp.