Learn DSA
Depth-First Search
Greedy Algorithms
Number of Islands
DESCRIPTION (credit 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:
Output:
💻 Desktop Required
The code editor works best on larger screens. Please open this page on your computer to write and run code.
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.
Run your code to see results here
Have suggestions or found something wrong?
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] = '0'if 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] = '0'if 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] = '0'if 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
Login to track your progress
Your account is free and you can post anonymously if you choose.