PHP code example of nexus-scholar / graph-algorithms

1. Go to this page and download the library: Download nexus-scholar/graph-algorithms library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

nexus-scholar / graph-algorithms example snippets


use Mbsoft\Graph\Algorithms\Centrality\PageRank;

$pagerank = new PageRank(
    dampingFactor: 0.85,
    maxIterations: 100,
    tolerance: 1e-6,
);

$scores = $pagerank->compute($graph);
arsort($scores);

use Mbsoft\Graph\Algorithms\Pathfinding\Dijkstra;

$dijkstra = new Dijkstra();
$path = $dijkstra->find($graph, 'start', 'destination');

if ($path !== null) {
    $nodes = $path->nodes;
    $cost = $path->cost;
}

use Mbsoft\Graph\Algorithms\Pathfinding\AStar;

$astar = new AStar(
    heuristicCallback: fn (string $from, string $to): float => manhattanDistance($from, $to),
);

$path = $astar->find($graph, 'start', 'destination');

use Mbsoft\Graph\Algorithms\Traversal\Bfs;
use Mbsoft\Graph\Algorithms\Traversal\Dfs;

$bfsOrder = (new Bfs())->traverse($graph, 'startNode');
$dfsOrder = (new Dfs())->traverse($graph, 'startNode');

use Mbsoft\Graph\Algorithms\Components\StronglyConnected;

$components = (new StronglyConnected())->findComponents($graph);

use Mbsoft\Graph\Algorithms\Pathfinding\Dijkstra;

$distanceOptimized = new Dijkstra(
    fn (array $attrs, string $from, string $to): float => $attrs['distance'] ?? 1.0,
);