Carol has a matrix of n rows and m columns. Every grid (the coordinate are from 1) in the matrix has a number representing its color. If you stand in one grid, you can move to an adjacent grid if you satisfy these two requirements:

If you stand on (x, y), then (x + 1, y), (x  1, y), (x, y  1), (x, y + 1) are adjacent to you.

The color in your position are the same as the grid you are going to.
If you can reach one grid from another grid, then they are in the same group.
Now, you need to calculate how many groups the matrix has.
The most important thing is the first column are adjacent to the last column.