LeetCode: 695. Max Area of Island

LeetCode: 695. Max Area of Island

695. Max Area of Island

Summary

Calculate the maximum area of an island.

Approach

Mark visited cells and compute each island's area with DFS.

Function

Initialization:

  • visited: an m * n array.
  • best: initialized to zero.

Function to calculate area:

Arguments:

  • i, j: indices from which to start exploring.

Returns:

  • The area of the island.

If i, j is out of range, return 0. If i, j is already marked as visited, return 0. Mark i, j as visited. If grid[i][j] is 0 (not part of an island), return 0.

Set area = 1. Search the four connected neighbors with DFS. For each cell in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]: area += explore(...) Return area.

Set best = 0. For each i, j in the m * n matrix: best = max(best, explore(i, j))

Return best.

Complexity

Time Complexity: O(MN) Space Complexity: O(MN)