-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpaiza15.php
46 lines (37 loc) · 1.17 KB
/
paiza15.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
list($H, $W) = array_map('intval', explode(' ', trim(fgets(STDIN))));
$grid = [];
while($line = trim(fgets(STDIN))) {
$grid[] = str_split(trim($line));
}
$visited = array_fill(0, $H, array_fill(0, $W, false));
$count = 0;
function bfs($grid, $visited, $startRow, $startCol, $H, $W) {
$directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];
$queue = new SplQueue();
$queue->enqueue([$startRow, $startCol]);
$visited[$startRow][$startCol] = true;
while (!$queue->isEmpty()) {
list($row, $col) = $queue->dequeue();
foreach ($directions as $direction) {
$newRow = $row + $direction[0];
$newCol = $col + $direction[1];
if ($newRow >= 0 && $newRow < $H && $newCol >= 0 && $newCol < $W
&& !$visited[$newRow][$newCol] && $grid[$newRow][$newCol] == '.') {
$visited[$newRow][$newCol] = true;
$queue->enqueue([$newRow, $newCol]);
}
}
}
return $visited;
}
for ($i = 0; $i < $H; $i++) {
for ($j = 0; $j < $W; $j++) {
if (!$visited[$i][$j] && $grid[$i][$j] == '.') {
$visited = bfs($grid, $visited, $i, $j, $H, $W);
$count++;
}
}
}
echo $count;
?>