Algo-Sim › Grid Graphs
Max Area of Island
Medium · Grid Graphs · step through it in Java, Python and C++ on your own input
Return the number of cells in the largest island (0 if there is no land).
Problem
Given a grid of 1 (land) and 0 (water), return the area, in cells, of the largest island, where an island is a group of land cells joined horizontally or vertically. Return 0 if there is no land.
Constraints
- 1 ≤ m, n ≤ 50
- grid[i][j] is 0 or 1
Edge cases to test
- No land:
0 - One big island
- Many single cells
Follow-up questions
- What if you may turn one 0 into a 1?
- Label each island with its size, then for each 0 add the sizes of distinct neighbouring islands (LC 827): O(mn).
- What is the cost?
- O(mn) time; each cell is sunk once.
Solution
Java
public int maxAreaOfIsland(int[][] grid) {
int best = 0;
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] != 1) continue;
best = Math.max(best, dfs(grid, r, c));
}
}
return best;
}
private int dfs(int[][] grid, int r, int c) {
if (r < 0 || c < 0 || r >= grid.length || c >= grid[0].length || grid[r][c] != 1) return 0;
grid[r][c] = 0;
int area = 1;
area += dfs(grid, r + 1, c);
area += dfs(grid, r - 1, c);
area += dfs(grid, r, c + 1);
area += dfs(grid, r, c - 1);
return area;
}Python
def max_area_of_island(grid):
best = 0
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] != 1:
continue
best = max(best, dfs(grid, r, c))
return best
def dfs(grid, r, c):
if not (0 <= r < len(grid) and 0 <= c < len(grid[0])) or grid[r][c] != 1:
return 0
grid[r][c] = 0
area = 1
area += dfs(grid, r + 1, c)
area += dfs(grid, r - 1, c)
area += dfs(grid, r, c + 1)
area += dfs(grid, r, c - 1)
return areaC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>> &grid) {
int best = 0;
for (int r = 0; r < int(grid.size()); r++) {
for (int c = 0; c < int(grid[0].size()); c++) {
if (grid[r][c] != 1)
continue;
best = std::max(best, dfs(grid, r, c));
}
}
return best;
}
int dfs(vector<vector<int>> &grid, int r, int c) {
if (r < 0 || c < 0 || r >= int(grid.size()) || c >= int(grid[0].size()) || grid[r][c] != 1)
return 0;
grid[r][c] = 0;
int area = 1;
area += dfs(grid, r + 1, c);
area += dfs(grid, r - 1, c);
area += dfs(grid, r, c + 1);
area += dfs(grid, r, c - 1);
return area;
}
};
More Grid Graphs problems
- Flood Fill (Easy)
- Number of Islands (BFS) (Medium)
- Number of Islands (DFS) (Medium)
- Rotting Oranges (Medium)
- 01 Matrix (Medium)
- Walls and Gates (Medium)
- Shortest Path in Binary Matrix (Medium)
- Shortest Bridge (Medium)
- Shortest Path in a Grid with Obstacles Elimination (Hard)
- Surrounded Regions (Medium)
- Pacific Atlantic Water Flow (Medium)
- Path With Minimum Effort (Medium)
- Minimum Cost to Make at Least One Valid Path in a Grid (Hard)
- Swim in Rising Water (Hard)