MediumNo. 0695
Max Area of Island — LeetCode 695 Python Solution
- Pattern
- Union-Find
- Topics
- Depth-First Search, Breadth-First Search, Union Find, Array, Matrix
- On a study list
- NeetCode 150
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Example
- Input
- grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
- Output
- 6
- Explanation
- The answer is not 11, because the island must be connected 4-directionally.
Python solution
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
def dfs(i: int, j: int) -> int:
if grid[i][j] == 0:
return 0
ans = 1
grid[i][j] = 0
dirs = (-1, 0, 1, 0, -1)
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n:
ans += dfs(x, y)
return ans
m, n = len(grid), len(grid[0])
return max(dfs(i, j) for i in range(m) for j in range(n))Complexity
- Time
- O(V+E)
- Space · auxiliary
- O(V)
Pattern: Union-Find
Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 695. Max Area of Island is filed here because LeetCode tags it Union Find, which is the vocabulary this hub collects.
The union-find guide has the Python template for the pattern and the 83 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0130 | Surrounded Regions | Medium |
| 0200 | Number of Islands | Medium |
| 0827 | Making A Large Island | Hard |
| 1020 | Number of Enclaves | Medium |
| 1254 | Number of Closed Islands | Medium |
| 1267 | Count Servers that Communicate | Medium |
Frequently asked questions
- How hard is LeetCode 695. Max Area of Island?
LeetCode 695. Max Area of Island is rated Medium on LeetCode.
- What is the time complexity of LeetCode 695. Max Area of Island?
The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 695. Max Area of Island?
The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 695. Max Area of Island cover?
LeetCode 695. Max Area of Island is tagged Depth-First Search, Breadth-First Search, Union Find, Array and Matrix on LeetCode.