// C# Code to implement above approach
using System;
public class Solution {
// Function to check if it is valid
// to move on the next cell
static bool isValid(int row, int col, char[, ] grid,
int[, ] visited)
{
return (row < grid.GetLength(0)) && (row >= 0)
&& (col < grid.GetLength(1)) && (col >= 0)
&& (grid[row, col] == 'X')
&& (visited[row, col] == 0);
}
// Function to implement dfs
static void dfs(int row, int col, char[, ] grid,
int[, ] visited)
{
if (!isValid(row, col, grid, visited))
return;
visited[row, col] = 1;
dfs(row + 1, col, grid, visited);
dfs(row, col + 1, grid, visited);
dfs(row - 1, col, grid, visited);
dfs(row, col - 1, grid, visited);
}
// Function to count the total number of submatrices
static int xShape(char[, ] grid)
{
int n = grid.GetLength(0);
int m = grid.GetLength(1);
int[, ] visited = new int[n, m];
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (visited[i, j] == 0
&& grid[i, j] == 'X') {
dfs(i, j, grid, visited);
count++;
}
}
}
return count;
}
// Driver code
public static void Main(string[] args)
{
char[, ] grid
= new char[, ] { { 'X', 'O', 'X', 'X' },
{ 'O', 'O', 'X', 'X' },
{ 'X', 'X', 'O', 'O' },
{ 'O', 'O', 'X', 'X' },
{ 'X', 'O', 'O', 'O' } };
Console.WriteLine(xShape(grid));
}
}
// This code is contributed by karandeep1234