<?php
$grid = [
['S', '.', '.', '#', '.'],
['#', '#', '.', '#', '.'],
['.', '.', '.', '.', '.'],
['.', '#', '#', '#', '.'],
['.', '.', '.', 'G', '.'],
];
$rows = count($grid);
$cols = count($grid[0]);
$start = [0,0];
$goal = [4,3];
$directions = [
[1,0], [-1,0], [0,1], [0,-1]
];
// queue untuk BFS
$queue = [];
$queue[] = [$start[0], $start[1], 0]; // row, col, langkah
$visited = [];
$visited[$start[0]][$start[1]] = true;
while (!empty($queue)) {
[$r, $c, $dist] = array_shift($queue);
if ($r == $goal[0] && $c == $goal[1]) {
echo "Jarak terpendek: $dist\n";
break;
}
foreach ($directions as $d) {
$nr = $r + $d[0];
$nc = $c + $d[1];
if ($nr >= 0 && $nr < $rows && $nc >= 0 && $nc < $cols) {
if (!isset($visited[$nr][$nc]) && $grid[$nr][$nc] != '#') {
$visited[$nr][$nc] = true;
$queue[] = [$nr, $nc, $dist + 1];
}
}
}
}
?>
No comments:
Post a Comment