Techniques Used
- Graph
- Simple DFS
Prerequisite Problem Recommended
- 200 - Number of Islands
Approach
It is similar to the Number of Islands problem. We just need an additional variable to count the area of every island that we find. Then find the maximum area one.
- Initialize the
visited
matrix andmax_area_island
variable. - Apply a nested for loop, to visited all the elements of the grid with the following conditions
- if the current element has not been visited and is not water. ( != 0)
- initialize the
count
variable (it will store the area of the island formed by current element). - we are using
count
as an 1 element array to pass it by reference. - apply
dfs
for the current element to find its island area. - store the greater value between
max_island_area
andcount[0]
in themax_island_area
variable.
- initialize the
- if the current element has not been visited and is not water. ( != 0)
- In the
dfs
utility function,- Check for the boundary conditions, AND if the current element has been visited or not AND if the current element is land ( contains value of 1), and return accordingly.
- Now, mark the current element as visited.
- increment the
count
variable. - Apply the same
dfs
function in all the 4 directions of this element.
Complexity
- Time Complexity: O(mn) - Maximum area can be equal to whole grid.
- Space Complexity: O(mn) - Space for visited matrix.
Code
class Solution {
public int maxAreaOfIsland(int[][] grid) {
// find all the islands
// keep track of the number of elements in that island
// find the island with max_count
int m = grid.length;
int n = grid[0].length;
int max_area_island = 0;
boolean[][] visited = new boolean[m][n];
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(!visited[i][j] && grid[i][j] != 0){
int[] count = new int[1];
dfs(grid, i, j, visited, count);
max_area_island = Math.max(max_area_island, count[0]);
}
}
}
return max_area_island;
}
static void dfs(int[][] grid, int row, int col, boolean[][] visited, int[] count){
if(row < 0 || col < 0 || row >= grid.length || col >= grid[0].length || visited[row][col] || grid[row][col] == 0 ) return;
visited[row][col] = true;
count[0]++;
dfs(grid, row - 1, col, visited, count);
dfs(grid, row + 1, col, visited, count);
dfs(grid, row, col + 1, visited, count);
dfs(grid, row, col - 1, visited, count);
return;
}
}