#K16126. Maximal Island Area

    ID: 24510 Type: Default 1000ms 256MiB

Maximal Island Area

Maximal Island Area

You are given a 2D grid of integers, where 0 represents water and 1 represents land. An island is a group of adjacent 1's connected horizontally or vertically. Your task is to determine the area of the largest island in the grid. If there is no island, print 0.

Formally, if we denote the grid as \(G\) of dimensions \(n \times m\), an island is defined as a set of cells \(\{(i,j)\}\) where each cell has value 1 and for any two cells in the island there exists a path through adjacent (up, down, left, right) cells that are also equal to 1. The area is the number of cells in that island. Use Depth First Search (DFS) or Breadth First Search (BFS) to solve this problem.

Examples:

  • If the grid has no 1's then the answer is \(0\).
  • If the grid is:
1 1 0 0 0
1 1 0 0 0
0 0 0 1 1
0 0 0 1 1
  • The maximum island area is \(4\).

inputFormat

The first line of input contains two integers \(n\) and \(m\), the number of rows and columns respectively. Each of the next \(n\) lines contains \(m\) space-separated integers (either 0 or 1), representing the grid.

For example:

4 5
1 1 0 0 0
1 1 0 0 0
0 0 0 1 1
0 0 0 1 1

outputFormat

Output a single integer representing the maximum area of an island in the grid. If there is no island, output 0.

## sample
4 5
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0