// C# implementation of the approach
using System;
class GFG
{
static readonly int maxRow = 500;
static readonly int maxCol = 500;
static bool [,]visited = new bool[maxRow,maxCol];
// Function that return true if mat[row,col]
// is valid and hasn't been visited
static bool isSafe(String []M, int row, int col,
char c, int n, int l)
{
// If row and column are valid and element
// is matched and hasn't been visited then
// the cell is safe
return (row >= 0 && row < n) &&
(col >= 0 && col < l) &&
(M[row][col] == c &&
!visited[row,col]);
}
// Function for depth first search
static void DFS(String []M, int row, int col,
char c, int n, int l)
{
// These arrays are used to get row and column
// numbers of 4 neighbours of a given cell
int []rowNbr = {-1, 1, 0, 0};
int []colNbr = {0, 0, 1, -1};
// Mark this cell as visited
visited[row,col] = true;
// Recur for all connected neighbours
for (int k = 0; k < 4; ++k)
{
if (isSafe(M, row + rowNbr[k],
col + colNbr[k], c, n, l))
{
DFS(M, row + rowNbr[k],
col + colNbr[k], c, n, l);
}
}
}
// Function to return the number of
// connectewd components in the matrix
static int connectedComponents(String []M, int n)
{
int connectedComp = 0;
int l = M[0].Length;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < l; j++)
{
if (!visited[i,j])
{
char c = M[i][j];
DFS(M, i, j, c, n, l);
connectedComp++;
}
}
}
return connectedComp;
}
// Driver code
public static void Main(String[] args)
{
String []M = {"aabba", "aabba", "aaaca"};
int n = M.Length;
Console.WriteLine(connectedComponents(M, n));
}
}
// This code contributed by Rajput-Ji