#K4731. Connected Pallet Groups

    ID: 28170 Type: Default 1000ms 256MiB

Connected Pallet Groups

Connected Pallet Groups

You are given a warehouse represented as a 2D grid. Each cell in the grid contains either a 0 (representing an empty section) or a 1 (representing a pallet). Two pallets are considered connected if they are adjacent horizontally or vertically, i.e. their Manhattan distance is 1 ((|x_1 - x_2| + |y_1 - y_2| = 1)).

Your task is to count the number of connected groups of pallets present in the warehouse. A connected group is defined as a set of cells with value 1 where every cell is connected to at least one other cell in the group via the allowed adjacent moves (up, down, left, right).

For example, given the following warehouse grid:

1 1 0 0
0 1 0 1
1 0 0 1
0 0 1 1

The answer is 3 because there are three distinct groups of connected pallets.

inputFormat

The first line contains two space-separated integers (n) and (m), representing the number of rows and columns in the warehouse grid, respectively. This is followed by (n) lines, each containing (m) space-separated integers (either 0 or 1) representing the warehouse layout.

outputFormat

Output a single integer representing the number of connected groups of pallets.## sample

4 4
1 1 0 0
0 1 0 1
1 0 0 1
0 0 1 1
3