#K33702. Count the Number of Islands

    ID: 25146 Type: Default 1000ms 256MiB

Count the Number of Islands

Count the Number of Islands

You are given a grid of size \( m \times n \) where each cell contains either a 0 or a 1. A cell with value 1 represents a piece of land and a cell with value 0 represents water. An island is defined as a group of connected lands where connectivity is only allowed in the four cardinal directions (up, down, left, right). The entire grid is surrounded by water.

Your task is to determine the total number of islands in the grid.

Note: The input grid is provided via standard input, and the output (the number of islands) should be printed to standard output.

The grid is given in the following format:

  • The first line contains two integers \( m \) and \( n \) representing the number of rows and columns respectively.
  • The next \( m \) lines each contain \( n \) integers (either 0 or 1) separated by spaces.

For example, consider the grid below:

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

This grid contains 3 islands.

inputFormat

The first line of input contains two space-separated integers \( m \) and \( n \), indicating the grid's dimensions.

The following \( m \) lines each contain \( n \) space-separated integers (each either 0 or 1) representing the grid.

outputFormat

Output a single integer representing the number of islands found in the grid.

## sample
4 5
1 1 0 0 0
1 1 0 0 0
0 0 1 0 0
0 0 0 1 1
3