Problem Description
You are given an m * n matrix that represents a map.
Each cell of the matrix can have one of the following values:
1: land0: water
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume that all four edges of the grid are surrounded by water.
Write a function that takes the matrix and returns the number of islands in it.
Constraints
m == grid.lengthn == grid[i].length1 <= m, n <= 300- Allowed values in the matrix are
0or1
Examples
Input
[
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"],
]Answer: 1
Solution
To count the islands in the matrix, it's enough to find at least one cell of each island.
First, we create an island counter with an initial value of 0.
Then we go over all elements of the matrix and perform the following checks:
- if the value is
0, we simply skip it; - if the value is
1, we've hit an island: we increment the counter and recursively remove the island from the matrix.
After hitting an island, we remove it from the matrix so that it isn't counted again when checking subsequent elements.
This way, every time we meet a 1, we know for sure that we've found a new island.
export const numIslands = (grid: string[][]): number => {
let counter = 0;
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[i].length; j++) {
if (grid[i][j] == '1') {
counter++;
deepScan(grid, i, j);
}
}
}
return counter;
};
export const deepScan = (grid: string[][], i: number, j: number): void => {
grid[i][j] = '0';
if (j < grid[i].length - 1 && grid[i][j + 1] == '1') {
deepScan(grid, i, j + 1);
}
if (i < grid.length - 1 && grid[i + 1][j] == '1') {
deepScan(grid, i + 1, j);
}
if (j > 0 && grid[i][j - 1] == '1') {
deepScan(grid, i, j - 1);
}
if (i > 0 && grid[i - 1][j] == '1') {
deepScan(grid, i - 1, j);
}
};Complexity Analysis
Time Complexity
Since we traverse the whole matrix, the traversal costs O(m * n).
On top of that, island removal may be triggered, which in the worst case takes O(m * n) operations (if the whole matrix is filled with ones).
So the total complexity is O(2(m * n)), which simplifies to O(m * n).
Space Complexity
O(1): constant, since we only allocate additional memory for counters.