Depth-First Search
Number of Islands
DESCRIPTION (inspired by Leetcode.com)
You are given binary matrix grid of size m x n, where '1' denotes land and '0' signifies water. Determine the count of islands present in this grid. An island is defined as a region of contiguous land cells connected either vertically or horizontally, and it is completely encircled by water. Assume that the grid is bordered by water on all sides.
Input:
grid = [ [1,1,0,1], [1,1,0,1], [1,1,0,0], ]
Output:
2
Explanation
First Island
def numIslands(grid):if not grid:return 0rows, cols = len(grid), len(grid[0])count = 0def dfs(r, c):grid[r][c] = 0if r + 1 < rows and grid[r + 1][c] == 1:dfs(r + 1, c)if r > 0 and grid[r - 1][c] == 1:dfs(r - 1, c)if c + 1 < cols and grid[r][c + 1] == 1:dfs(r, c + 1)if c > 0 and grid[r][c - 1] == 1:dfs(r, c - 1)returnfor i in range(rows):for j in range(cols):if grid[i][j] == 1:count += 1dfs(i, j)return count
i = 0
0 / 19
Second Island
def numIslands(grid):if not grid:return 0rows, cols = len(grid), len(grid[0])count = 0def dfs(r, c):grid[r][c] = 0if r + 1 < rows and grid[r + 1][c] == 1:dfs(r + 1, c)if r > 0 and grid[r - 1][c] == 1:dfs(r - 1, c)if c + 1 < cols and grid[r][c + 1] == 1:dfs(r, c + 1)if c > 0 and grid[r][c - 1] == 1:dfs(r, c - 1)returnfor i in range(rows):for j in range(cols):if grid[i][j] == 1:count += 1dfs(i, j)return count
recursive call
0 / 9
Animated Solution
def numIslands(grid):if not grid:return 0rows, cols = len(grid), len(grid[0])count = 0def dfs(r, c):grid[r][c] = 0if r + 1 < rows and grid[r + 1][c] == 1:dfs(r + 1, c)if r > 0 and grid[r - 1][c] == 1:dfs(r - 1, c)if c + 1 < cols and grid[r][c + 1] == 1:dfs(r, c + 1)if c > 0 and grid[r][c - 1] == 1:dfs(r, c - 1)returnfor i in range(rows):for j in range(cols):if grid[i][j] == 1:count += 1dfs(i, j)return count
number of islands
0 / 46
Complexity Analysis
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(m * n) We visit each cell in the grid at most once. The outer loop iterates through all m * n cells, and the DFS marks each cell as visited by setting it to 0, so no cell is processed more than once.
Space Complexity: O(m * n) In the worst case, the entire grid is filled with land (1s), causing the DFS recursion stack to grow up to m * n deep.
Mark as read
Unlock Premium Coding Content
On This Page
Your account is free and you can post anonymously if you choose.