Last active
August 29, 2015 14:06
-
-
Save Leko/05ad2cfeb76aeb5ae9c2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
define('CELL_START', 'S'); | |
define('CELL_GOAL', 'G'); | |
define('CELL_WALL', '#'); | |
define('NA', -1); | |
function search($sx, $sy) { | |
global $maze, $visited; | |
$size = count($maze); | |
$moves = [[1, 0], [-1, 0], [0, 1], [0, -1]]; | |
$answer = PHP_INT_MAX; | |
$queue = []; | |
foreach($moves as $move) { | |
list($mx, $my) = $move; | |
$queue[] = [$sx + $mx, $sy + $my, 1]; | |
} | |
while(!empty($queue)) { | |
list($x, $y, $step) = array_pop($queue); | |
if($x < 0 || $size <= $x || $y < 0 || $size <= $y) continue; // 枠外判定 | |
if($maze[$x][$y] === CELL_WALL) continue; // 壁判定 | |
if($visited[$x][$y]) continue; // 訪問済み判定 | |
$visited[$x][$y] = 1; | |
if($maze[$x][$y] === CELL_GOAL) $answer = min($answer, $step); | |
foreach($moves as $move) { | |
list($mx, $my) = $move; | |
$queue[] = [$x + $mx, $y + $my, $step + 1]; | |
} | |
} | |
return $answer; | |
} | |
$stdin = file_get_contents('php://stdin'); | |
$maze = explode("\n", $stdin); | |
$visited = []; | |
for($y = 0; $y < count($maze); $y++) { | |
$visited[$y] = []; | |
for($x = 0; $x < strlen($maze[$y]); $x++) { | |
$visited[$y][$x] = 0; | |
} | |
} | |
for($x = 0; $x < count($maze); $x++) { | |
for($y = 0; $y < strlen($maze[$x]); $y++) { | |
if($maze[$x][$y] === CELL_START) { | |
$ans = search($x, $y); | |
echo ($ans === PHP_INT_MAX ? NA : $ans)."\n"; | |
break; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##### | |
#S#G# | |
#...# | |
#.#.# | |
#...# | |
##### |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment