Solutions
1. Depth First Search
O(rows * cols) time | O(rows * cols) space
Intuition
We can iterate through all the cells of the matrix.
If the cell is land, it is a part of an island, so we check this island size, keeping the largest one.
To check the size of the island we use DFS: recursively follow each land neighbour as far as it goes, counting every cell we pass.
We should also keep a set of visited cells to not traverse infinitely.
Algorithm
- Create a
largestinteger and avisitedhash set. - Iterate through the outer loop from the first row to the last row with
rowindex. - For each outer loop iteration, iterate through the inner loop from the first column to the last column with
colindex.- Count the island the cell at row
rowand columncolbelongs to withdfs, and updatelargestif that count is greater.
- Count the island the cell at row
- Return
largest. - In the
dfsfunction:- If the cell is outside the grid, its value is
0, or it was visited before, return0. - Otherwise mark the cell as visited, and return
1plus whatdfscounts for the cells above, below, to the left and to the right.
- If the cell is outside the grid, its value is
Code
Recursive implementation
Iterative implementation
2. Breadth First Search
O(rows * cols) time | O(rows * cols) space
Intuition
We can iterate through all the cells of the matrix.
If the cell is land, it is a part of an island, so we check this island size, keeping the largest one.
To check the size of the island we use BFS: put the cell in a queue, and every cell we take out of it puts its own land neighbours in, counting every cell we pass until the queue is empty.
We should also keep a set of visited cells to not traverse infinitely.
Algorithm
- Create a
largestinteger and avisitedhash set. - Iterate through the outer loop from the first row to the last row with
rowindex. - For each outer loop iteration, iterate through the inner loop from the first column to the last column with
colindex.- Count the island the cell at row
rowand columncolbelongs to withbfs, and updatelargestif that count is greater.
- Count the island the cell at row
- Return
largest. - In the
bfsfunction:- If the cell's value is
0or it was visited before, return0. - Otherwise mark the cell as visited and put it in the queue.
- While the queue has cells to take, take the one at the front, and put every cell above, below, to the left and to the right of it that is inside the grid, has value
1and was not visited before in the queue, marking each as visited. - Return how many cells went through the queue.
- If the cell's value is
Code
def largestIsland(grid: list[list[int]]) -> int: pass Press Visualise to step through your code.