Dijkstra::calculateRoad()   B
last analyzed

Complexity

Conditions 8
Paths 8

Size

Total Lines 31
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 22
c 1
b 0
f 0
nc 8
nop 5
dl 0
loc 31
rs 8.4444
1
<?php
2
3
    namespace PatchFind\Algorithm;
4
    
5
    class Dijkstra implements DijkstraInterface
6
    {
7
        /**
8
         * calculate road in graph
9
         *
10
         * @param  int   $startX
11
         * @param  int   $startY
12
         * @param  int   $endX
13
         * @param  int   $endY
14
         * @param  array $graph
15
         * @return array
16
         */
17
        public function calculateRoad($startX, $startY, $endX, $endY, $graph){
18
            $a = "(".$startX.",".$endX.")";
19
            $b = "(".$startY.",".$endY.")";
20
            
21
            $short = array(); 
22
            $query = array();
23
            foreach(array_keys($graph) as $v) $query[$v] = 99999;
24
            $query[$a] = 0;
25
26
            while(!empty($query)){
27
                $min = array_search(min($query), $query);
28
                if($min === $b) break;
29
                foreach($graph[$min] as $key => $v){
30
                    if(!empty($query[$key]) && $query[$min] + $v < $query[$key]){
31
                        $query[$key] = $query[$min] + $v;
32
                        $short[$key] = array($min, $query[$key]);
33
                    }
34
                }
35
                unset($query[$min]);
36
            }
37
38
            $path = array();
39
            $pos = $b;
40
            while($pos != $a){
41
                $path[] = $pos;
42
                $pos = $short[$pos][0];
43
            }
44
            $path[] = $a;
45
            $path = array_reverse($path);
46
47
            return $path;
48
        }
49
    }