200. Number of Islands #109
-
Topics: Given an An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
We can use Depth-First Search (DFS) to explore and count the islands in the given 2D binary grid. The approach involves traversing the grid and performing DFS to mark all connected land cells for each island. Let's implement this solution in PHP: 200. Number of Islands <?php
class Solution {
/**
* @param String[][] $grid
* @return Integer
*/
function numIslands($grid) {
if (empty($grid) || empty($grid[0])) {
return 0;
}
$m = count($grid);
$n = count($grid[0]);
$islands = 0;
for ($i = 0; $i < $m; $i++) {
for ($j = 0; $j < $n; $j++) {
if ($grid[$i][$j] == '1') {
$this->dfs($grid, $i, $j, $m, $n);
$islands++;
}
}
}
return $islands;
}
private function dfs(&$grid, $x, $y, $m, $n) {
// Check if the current cell is out of bounds or water
if ($x < 0 || $x >= $m || $y < 0 || $y >= $n || $grid[$x][$y] != '1') {
return;
}
// Mark the current cell as visited
$grid[$x][$y] = 'x';
// Perform DFS in all four directions
$this->dfs($grid, $x + 1, $y, $m, $n);
$this->dfs($grid, $x - 1, $y, $m, $n);
$this->dfs($grid, $x, $y + 1, $m, $n);
$this->dfs($grid, $x, $y - 1, $m, $n);
}
}
// Example usage
$solution = new Solution();
$grid1 = [
["1", "1", "1", "1", "0"],
["1", "1", "0", "1", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "0", "0", "0"]
];
$grid2 = [
["1", "1", "0", "0", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "1", "0", "0"],
["0", "0", "0", "1", "1"]
];
echo "Output for grid1: " . $solution->numIslands($grid1) . "\n"; // Output: 1
echo "Output for grid2: " . $solution->numIslands($grid2) . "\n"; // Output: 3
?> Explanation:
How It Works
This approach efficiently counts the number of islands by exploring each land cell and marking all connected cells, ensuring that each island is counted only once. |
Beta Was this translation helpful? Give feedback.
We can use Depth-First Search (DFS) to explore and count the islands in the given 2D binary grid. The approach involves traversing the grid and performing DFS to mark all connected land cells for each island.
Let's implement this solution in PHP: 200. Number of Islands