#C4150. Counting Islands in a Grid

    ID: 47657 Type: Default 1000ms 256MiB

Counting Islands in a Grid

Counting Islands in a Grid

You are given a grid representing a map where each cell is either land ('1') or water ('0'). An island is formed by connecting adjacent lands horizontally or vertically. Your task is to count the number of islands present in the grid.

The grid is provided as input via standard input. The first line of input contains two integers r and c which represent the number of rows and columns respectively. This is followed by r lines, each containing c space-separated characters ('0' or '1').

Note: If there are no cells (i.e. r = 0), the number of islands is considered to be 0.

Your solution should output the count of islands to standard output.

inputFormat

The input is given from standard input in the following format:

r c
row1
row2
...
row_r

Where:

  • r is the number of rows in the grid.
  • c is the number of columns in the grid.
  • Each of the next r lines contains c space-separated characters (each either '0' or '1'), representing the grid.</p>

    outputFormat

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

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