-
Notifications
You must be signed in to change notification settings - Fork 46
/
php.php
46 lines (38 loc) · 1.06 KB
/
php.php
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
<?php
$nodes = $visited = $visitCache = [];
function readPlaces()
{
global $nodes, $visited;
$lines = [];
$fp = fopen('agraph', 'rb');
$nodeCount = trim(fgets($fp));
while (false !== ($line = fgets($fp))) {
$lines[] = str_getcsv(trim($line), ' ');
}
$nodes = array_fill(0, $nodeCount, []);
$visited = array_fill(0, $nodeCount, false);
foreach($lines as $line) {
$nodes[(int)$line[0]][(int)$line[1]] = (int)$line[2];
}
}
function getLongestPath($nodeId)
{
global $nodes, $visited;
$visited[$nodeId] = true;
$neighbors = $nodes[$nodeId];
$max = 0;
foreach($neighbors as $neighborId => $neighborCost) {
if (!$visited[$neighborId]) {
$dist = $neighborCost + getLongestPath($neighborId, $nodeId);
if ($dist > $max) {
$max = $dist;
}
}
}
$visited[$nodeId] = false;
return $max;
}
readPlaces();
$start = microtime(true);
$length = getLongestPath(0);
echo $length . ' LANGUAGE PHP ' . round((microtime(true) - $start) * 1000) . "\n";