#K42027. Count Islands in a Matrix
Count Islands in a Matrix
Count Islands in a Matrix
You are given a matrix of characters. Your task is to count the number of islands in the matrix. An island is defined as a group of adjacent cells (connected horizontally or vertically) that contain the same character. For example, in the matrix below:
\( \begin{matrix} a & a & b & b \\ a & c & c & b \\ a & a & c & d \\ e & e & e & d \end{matrix} \)
There are 5 islands. Note that if the matrix is empty, the output should be 0.
Input/Output: The input is read from standard input (stdin) and the answer is written to standard output (stdout).
inputFormat
The first line of input contains two integers \( n \) and \( m \) representing the number of rows and columns in the matrix, respectively. If \( n = 0 \) or \( m = 0 \), the matrix is considered empty. The next \( n \) lines each contain \( m \) space-separated characters representing the matrix.
For example:
4 4 a a b b a c c b a a c d e e e d
outputFormat
Output a single integer representing the number of islands in the given matrix.
## sample4 4
a a b b
a c c b
a a c d
e e e d
5