A grid of size NxM where each cell of the grid is filled with  some color. Find minimum number of clicks to make monochromatic grid (having one color). Problem reference (https://www.urionlinejudge.com.br/challenges/en/4b85c9eff62f37e3d169f4f62b67a6b655a6ccb1.html )

When the player clicks on any cell of the grid of color α, the cell in the top-leftmost corner of the grid, of color β, receives the color α, but not only it: all those cells which are connected to the source by paths which use only the colors α or β also receive the color α. 

The connection between cells should be considered only in the horizontal and vertical directions to form the paths. For example, when the player clicks on the cell highlighted in the figure to the left, the grid receives the coloring of the figure to the right.

find minimum number of clicks to make monochromatic grid

Test Cases:

Expected output:

How to find minimum number of clicks to make monochromatic grid