-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathDijkstra_Algorithm.php
More file actions
82 lines (69 loc) · 2.06 KB
/
Copy pathDijkstra_Algorithm.php
File metadata and controls
82 lines (69 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
// PHP program to implement Dijkstra's algorithm.
// Also known as single-source shortest path algorithm.
// It is a Greedy algorithm.
// function to find unvisited vertex with minimum distance
function getMinVertex($dist, $visited, $n){
$minVertex = -1;
for($i = 0; $i < $n; ++$i){
if(!$visited[$i] && (($minVertex == -1) || ($dist[$minVertex] > $dist[$i])) ){
$minVertex = $i;
}
}
return $minVertex;
}
function dijkstra($graph, $vertices){
$visited = array();
$dist = array();
for($i = 0; $i < $vertices; ++$i){
$visited[$i] = false;
$dist[$i] = PHP_INT_MAX;
}
// 0 is the source/starting vertex
$dist[0] = 0;
for($i = 0; $i < $vertices-1; ++$i){
$minVertex = getMinVertex($dist, $visited, $vertices);
// Mark the minVertex as visited
$visited[$minVertex] = true;
// Explore all unvisited neighbours of minVertex
// and update the dist array if required
for($j = 0; $j < $vertices; ++$j){
if($graph[$minVertex][$j] != 0 && !$visited[$j]){
$currD = $dist[$minVertex] + $graph[$minVertex][$j];
if($dist[$j] > $currD){
$dist[$j] = $currD;
}
}
}
}
// Print the vertices and their corresponding distances from the source vertex
echo "Vertex\tDistance from source\n";
for($k = 0; $k < $vertices; ++$k){
echo $k."\t".$dist[$k]."\n";
}
}
// Sample Graph (Sample Input) - Adjacency Matrix representation
$graph = array(
array(0, 3, 0, 5),
array(3, 0, 1, 0),
array(0, 1, 0, 8),
array(5, 0, 8, 0)
);
// Function for Dijkstra'a algorithm
dijkstra($graph, 4);
/*
Sample Input:
$graph = array(
array(0, 3, 0, 5),
array(3, 0, 1, 0),
array(0, 1, 0, 8),
array(5, 0, 8, 0)
);
Sample Output:
Vertex Distance from source
0 0
1 3
2 4
3 5
*/
?>