0% completed
Solution: Number of Islands
On This Page
Problem Statement
Why this is an Island problem
Solution
Code (DFS)
Code (BFS)
Code (BFS with visited matrix)
Problem Statement
Given a 2D array (i.e., a matrix) containing only 1s (land) and 0s (water), count the number of islands in it.
An island is a connected set of 1s (land) and is surrounded by either an edge or 0s (water). Each cell is considered connected to other cells horizontally or vertically (not diagonally).
Example 1
Input: matrix =
Output: 3
Explanation: The matrix has three islands. See the highlighted cells below.
Example 2
Input: matrix =
Output: 1
Explanation: The matrix has only one island. See the highlighted cells below.
Constraints:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 300matrix[i][j] is '0' or '1'.
Why this is an Island problem
| What the question says | The signal it matches |
|---|---|
| "count the number of islands in it" | how many separate connected areas the grid contains |
| "connected to other cells horizontally or vertically" | cells are joined to their neighbours by position |
| "An island is a connected set of 1s" | the wording includes island |
This is the count the regions variant: add one for each traversal you start.
The closest alternative. A normal graph traversal, and Number of Provinces from the previous chapter is the problem to compare. It counted groups the same way: start a traversal at every unvisited point, and count the starts.
The difference is where the connections come from. There, the matrix stored them. Here, no list of connections exists at all. A cell's connections are the four cells around it, computed from its position. Building an adjacency list for a grid of up to 90,000 cells would only restate the grid. Union Find also counts islands, by joining each land cell to the land cells beside it, and it is a fine second answer.
Solution
We can traverse the matrix linearly to find islands.
Whenever we find a cell with the value '1' (i.e., land), we have found an island. Using that cell as the root node, we will perform a Depth First Search (DFS) or Breadth First Search (BFS) to find all of its connected land cells. During our DFS or BFS traversal, we will find and mark all the horizontally and vertically connected land cells.
We need to have a mechanism to mark each land cell to ensure that each land cell is visited only once. To mark a cell visited, we have two options:
- We can update the given input matrix. Whenever we see a '1', we will make it '0'.
- A separate boolean matrix can be used to record whether or not each cell has been visited.
Following is the DFS or BFS traversal of the example-2 mentioned above:
Step 1. A 1 is land and a 0 is water, and two land cells belong to the same island when they touch sideways or vertically, never diagonally. The plan is one scan across every cell. Most cells will be water, or land already visited, and both are skipped. The moment an unvisited land cell turns up, it must belong to an island nobody has counted yet, so the count goes up by one and a traversal from that cell marks the whole island as visited. That marking is what stops the same island being counted again.
1 of 6
By following the above algorithm, every time DFS or BFS is triggered, we are sure that we have found an island. We will keep a running count to calculate the total number of islands.
Below, we will see three solutions based on:
- DFS
- BFS
- BFS with visited matrix
Code (DFS)
Here is what our DFS algorithm will look like. We will update the input matrix to mark cells visited.
Time Complexity
Time complexity of the above algorithm will be O(M*N), where ‘M’ is the number of rows and 'N' is the number of columns of the input matrix. This is due to the fact that we have to traverse the whole matrix to find the islands.
Space Complexity
DFS recursion stack can go M*N deep when the whole matrix is filled with '1's. Hence, the space complexity will be O(M*N), where ‘M’ is the number of rows and 'N' is the number of columns of the input matrix.
Code (BFS)
Here is what our BFS algorithm will look like. We will update the input matrix to mark cells visited.
Time Complexity
Time complexity of the above algorithm will be O(M*N), where ‘M’ is the number of rows and 'N' is the number of columns.
Space Complexity
Space complexity of the above algorithm will be O(min(M,N). In the worst case, when the matrix is completely filled with land cells, the size of the queue can grow up to min(M,N).
Code (BFS with visited matrix)
Here is what our BFS algorithm will look like. We will keep a separate boolean matrix to record whether or not each cell has been visited.
Time Complexity
Time complexity of the above algorithm will be O(M*N), where ‘M’ is the number of rows and 'N' is the number of columns.
Space Complexity
Because of the visited array and max size of the queue, the space complexity will be O(M*N), where ‘M’ is the number of rows and 'N' is the number of columns of the input matrix.
lejafilip
· 2 years ago
It is very important in FAANG interview, e.g. to Google. As I see it should be second one yes? Because we have TC: O(m*n) and SC: O(M or N) so it is linear in SC.
Rest have square in SC
Anand Mohan
· 3 years ago
Given :
DFS recursion stack can go deep when the whole matrix is filled with '1's. Hence, the space complexity will be , where ‘M’ is the number of rows and 'N' is the number of columns of the input matrix.
All the matrix element will not be in one recursion stack. It will part of call back to left and right sub-path. So, the space complexity should be less then (M*N)
I think for DFS as well the Space Complexity would be O(min(M, N))
Please correct me If I am wrong.
Mike Xu
· 4 years ago
To clarify the space complexity of BFS traversal of a matrix:
When you start traversing a matrix from the corner, the maximum number of cells/nodes you can have in the queue is k where k is the number of cells on a diagonal line in the matrix, which means k = min(M, N).
When you start traversing a matrix from the centre, the maximum number of cells/nodes you can have in the queue is {1, 4, 8, 12, 16, ..., 4i} where i is the i-th layer. And such cells fit in a matrix of min size {1, 4, 9, 16, 25, ..., i*i} respectively. We know that i is min(M, N), so yet again we have space complexity of O(4 * min(M, N)) which is O(min(M,N)).
sweetykumari
· 4 years ago
Hi , pls anyone share BFS code in C#.
evmorov
· 4 years ago
When can BFS be useful? For me, it looks like a more complicated version of DFS.
Smoke
· 4 years ago
Introduction/Solution lacks additional explanation. Why use DFS/BFS? What is the connection to those technique is not explained at all.
Manthan
· 4 years ago
can someone please explain what does this do and why are we doing this? Queue neighbors = new LinkedList(); neighbors.add(new int[] { x, y }); while (!neighbors.isEmpty()) { int row = neighbors.peek()[0]; int col = neighbors.peek()[1]; neighbors.remove();
Runyao Fan
· 4 years ago
Why is it that the BFS solution has a space complexity of O(min(M, N))? Why doesn't the queue size grow beyond min(M, N)?
Richard Yuan
· 4 years ago
Is there a specific reason why you used neighbors.extend() for a deque rather than neighbors.append()? The iterable only contains a single tuple in this case.
Mikhail Putilov
· 4 years ago
Why space complexity for BFS is min (M*N) ? what does it even mean?
Reading Progress
0%
On This Page
Problem Statement
Why this is an Island problem
Solution
Code (DFS)
Code (BFS)
Code (BFS with visited matrix)