Guest User

Untitled

a guest
Jan 22nd, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. <?
  2. // Why do we need the nodes?
  3. //$nodes = json_decode('[{"x":3,"y":6,"id":0},{"x":1,"y":1,"id":1},{"x":3,"y":1,"id":2},{"x":3,"y":4,"id":3},{"x":5,"y":1,"id":4},{"x":6,"y":1,"id":5},{"x":4,"y":3,"id":6},{"x":1,"y":6,"id":7},{"x":4,"y":6,"id":8},{"x":6,"y":6,"id":9},{"x":3,"y":9,"id":10},{"x":6,"y":11,"id":11}]');
  4. $paths = json_decode('[[0,1],[0,2],[0,3],[3,2],[3,6],[6,4],[6,5],[3,9],[9,9],[9,10],[10,0],[10,11],[11,10],[10,8],[8,3],[3,1]]');
  5.  
  6. // Convert paths to a hash: from -> [to]
  7. $newPaths = array();
  8. foreach($paths as $path) {
  9. if (!$newPaths[$path[0]]) $newPaths[$path[0]] = array();
  10. array_push($newPaths[$path[0]], $path[1]);
  11. }
  12. $paths = $newPaths;
  13.  
  14. // Use a Depth First Search, where:
  15. // $paths is the original $paths array
  16. // $visited are the nodes that we already visited (in order to avoid loops)
  17. // $from is the node where we are parting from
  18. // $to is the node where we want to arrive
  19. // $result is the result that will finally be returned
  20. function findPath(&$paths, &$visited, $from, $to, &$result) {
  21. $next = $paths[$from];
  22. if (!$next) return false;
  23.  
  24. foreach($next as $node) {
  25. if ($node == $to) {
  26. array_push($result, $from);
  27. array_push($result, $to);
  28. return $result;
  29. }
  30.  
  31. if ($visited[$node]) continue;
  32.  
  33. $visited[$node] = true;
  34. array_push($result, $from);
  35. if (findPath($paths, $visited, $node, $to, $result)) {
  36. return $result;
  37. }
  38. array_pop($result);
  39. unset($visited[$node]);
  40. }
  41. }
  42.  
  43. $result = array();
  44. $visited = array();
  45. findPath($paths, $visited, '0', '11', $result);
  46. print_r($result);
  47. ?>
Add Comment
Please, Sign In to add comment