Description: Robot Movements
A robot is located at the top-left corner of a 4×4 grid. The robot can move either up, down, left, or right, but can not visit the same spot twice. The robot is trying to reach the bottom-right corner of the grid.
Input sample:
There is no input for this program.
Output sample:
Print out the unique number of ways the robot can reach its destination. (The number should be printed as an integer whole number eg. if the answer is 10 (its not !!), print out 10, not 10.0 or 10.00 etc)
My Solution:
#!/usr/bin/php <?php class GridHelper { private $d1 = 1; private $d2 = 1; private $saved_paths = array(); //successful paths private $visited = array("1,1"=>true); //visited points (in a path) private $path = ""; //StringBuffer of x,y paths /*$path = x,y x1,y1, x2,y2, 4,4 */ private $fail = 0; //total failures since last success function __construct() { } public function __tostring() { return "GridHelper"; } public function seek() { while ($this->fail < 2000) { //200,000 $this->reset(); $this->path(); } //foreach($this->saved_paths as $path) { print $path."\n"; } return count($this->saved_paths); } public function path() { $point = $this->getNextPoint(); $point_as_string = join(",",$point); if ($point_as_string == "0,0") { $this->fail += 1; $this->path = ""; return; } if ($point_as_string == "4,4") { if (!isset($this->saved_paths[$this->path])) { $this->saved_paths[$this->path] = $this->path; $this->fail = 0; } $this->path = ""; return; } return $this->path(); } public function reset() { $this->d1 = 1; $this->d2 = 1; $this->visited = array("1,1"=>true); } private function getNextPoint() { $x = array(); //Add in our choices if (($this->d1 != 1)&& (!isset($this->visited[join(",",array($this->d1 -1,$this->d2))]))) { array_push($x,array($this->d1 -1,$this->d2)); } if (($this->d1 != 4) &&(!isset($this->visited[join(",",array($this->d1 +1,$this->d2))]))) { array_push($x,array($this->d1 +1,$this->d2)); } if (($this->d2 != 1) &&(!isset($this->visited[join(",",array($this->d1,$this->d2 -1))]))) { array_push($x,array($this->d1,$this->d2 -1)); } if (($this->d2 != 4) &&(!isset($this->visited[join(",",array($this->d1,$this->d2 +1))]))) { array_push($x,array($this->d1,$this->d2 +1)); } $l = count($x); $new_point_array = array(0,0); //Default is no choice if ($l > 0) { //If the length of X is > 0, we have choices. shuffle($x); $new_point_array = $x[array_rand($x,1)]; $this->d1 = $new_point_array[0]; $this->d2 = $new_point_array[1]; $new_point_array_as_string = join(",",$new_point_array); $this->visited[$new_point_array_as_string] = true; $this->path .= $new_point_array_as_string." "; } return $new_point_array; } } $g = new GridHelper(); print $g->seek()."\n"; exit; ?>
