|
| 1 | +class Status { |
| 2 | + var $key; |
| 3 | + var $i; |
| 4 | + var $j; |
| 5 | + function __construct($key, $i, $j) { |
| 6 | + $this->key = $key; |
| 7 | + $this->i = $i; |
| 8 | + $this->j = $j; |
| 9 | + } |
| 10 | +} |
| 11 | + |
| 12 | +class Solution { |
| 13 | + |
| 14 | + /** |
| 15 | + * @param String[] $grid |
| 16 | + * @return Integer |
| 17 | + */ |
| 18 | + function shortestPathAllKeys($grid) { |
| 19 | + $success = 0; |
| 20 | + $startI = 0; |
| 21 | + $startJ = 0; |
| 22 | + $rows = count($grid); |
| 23 | + $cols = strlen($grid[0]); |
| 24 | + for ($i = 0; $i < $rows; $i++) { |
| 25 | + for ($j = 0; $j < $cols; $j++) { |
| 26 | + $c = $grid[$i][$j]; |
| 27 | + if ($c >= 'A' && $c <= 'F') { |
| 28 | + $success |= 1 << (ord($c) - ord('A')); |
| 29 | + } |
| 30 | + |
| 31 | + if ($c == '@') { |
| 32 | + $startI = $i; |
| 33 | + $startJ = $j; |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + $dist = array_fill(0, 1 << 6, array_fill(0, $rows, array_fill(0, $cols, 2147483647))); |
| 38 | + $queue = []; |
| 39 | + array_push($queue, new Status(0, $startI, $startJ)); |
| 40 | + $dist[0][$startI][$startJ] = 0; |
| 41 | + $path = 0; |
| 42 | + $dirs = [[-1, 0], [0, 1], [1, 0], [0, -1]]; |
| 43 | + while (!empty($queue)) { |
| 44 | + $size = count($queue); |
| 45 | + while ($size-- > 0) { |
| 46 | + $status = array_pop($queue); |
| 47 | + $key = $status->key; |
| 48 | + $x = $status->i; |
| 49 | + $y = $status->j; |
| 50 | + if ($key == $success) return $path; |
| 51 | + foreach ($dirs as $dir) { |
| 52 | + $xx = $x + $dir[0]; |
| 53 | + $yy = $y + $dir[1]; |
| 54 | + if ($xx >= 0 && $xx < $rows && $yy >= 0 && $yy < $cols && $grid[$xx][$yy] != '#') { |
| 55 | + $nextKey = $key; |
| 56 | + $c = $grid[$xx][$yy]; |
| 57 | + if ($c >= 'a' && $c <= 'f') { |
| 58 | + $nextKey = $key | (1 << (ord($c) - ord('a'))); |
| 59 | + } |
| 60 | + |
| 61 | + if ($c >= 'A' && $c <= 'F') { |
| 62 | + if (($nextKey & (1 << (ord($c) - ord('A')))) == 0) continue; |
| 63 | + } |
| 64 | + |
| 65 | + if ($path + 1 < $dist[$nextKey][$xx][$yy]) { |
| 66 | + $dist[$nextKey][$xx][$yy] = $path + 1; |
| 67 | + array_unshift($queue, new Status($nextKey, $xx, $yy)); |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | + $path++; |
| 73 | + } |
| 74 | + return -1; |
| 75 | + } |
| 76 | +} |
0 commit comments