#K46387. Minimum Patrol Stations

    ID: 27965 Type: Default 1000ms 256MiB

Minimum Patrol Stations

Minimum Patrol Stations

You are given a representation of a city as a grid with R representing roads and B representing buildings. A patrol station placed on any road cell can cover all road cells in the same connected component (cells that are adjacent horizontally or vertically). Your task is to determine the minimum number of patrol stations required so that every road cell is patrolled.

Formally, for each test case, you are given an integer T representing the number of test cases. Each test case starts with two integers N and M denoting the number of rows and columns of the grid. This is followed by N lines, each containing a string of length M. The goal is to count the number of connected components consisting solely of the character R.

The connectivity is defined in the four cardinal directions (up, down, left, right). In other words, two R cells belong to the same connected component if they are adjacent (not diagonally) or can be connected via a sequence of adjacent road cells.

Count the number of such components; this number is the minimum number of patrol stations needed.

inputFormat

The first line contains an integer T, the number of test cases. Each test case is specified as follows:

  • The first line contains two integers N and M — the number of rows and columns of the grid.
  • The next N lines each contain a string of length M representing the grid. The character R denotes a road and B denotes a building.

Input is given via standard input (stdin).

outputFormat

For each test case, output a single line containing one integer — the minimum number of patrol stations required for that test case. Output should be sent to standard output (stdout).

## sample
3
3 3
RRR
RBB
RRR
4 4
RRBB
RBBR
BBRR
BBRR
2 2
RB
BR
1

2 2

</p>