// C# Program to find the number of islands
// using DFS with additional matrix
using System;
class GfG {
// A function to check if a given
// cell (r, c) can be included in DFS
static bool isSafe(char[,] grid, int r, int c, bool[,] visited) {
int row = grid.GetLength(0);
int col = grid.GetLength(1);
// r is in range, c is in range, value
// is 'L' and not yet visited
return (r >= 0 && r < row && c >= 0 && c < col && grid[r, c] == 'L' && !visited[r, c]);
}
// A utility function to do DFS for a
// 2D boolean matrix. It only considers
// the 8 neighbours as adjacent vertices
static void dfs(char[,] grid, int r, int c, bool[,] visited) {
int[] rNbr = { -1, -1, -1, 0, 0, 1, 1, 1 };
int[] cNbr = { -1, 0, 1, -1, 1, -1, 0, 1 };
visited[r, c] = true;
for (int k = 0; k < 8; k++) {
int newR = r + rNbr[k];
int newC = c + cNbr[k];
if (isSafe(grid, newR, newC, visited)) {
dfs(grid, newR, newC, visited);
}
}
}
static int countIslands(char[,] grid) {
int row = grid.GetLength(0);
int col = grid.GetLength(1);
bool[,] visited = new bool[row, col];
int count = 0;
for (int r = 0; r < row; r++) {
for (int c = 0; c < col; c++) {
if (grid[r, c] == 'L' && !visited[r, c]) {
dfs(grid, r, c, visited);
count++;
}
}
}
return count;
}
static void Main() {
char[,] grid = {
{ 'L', 'L', 'W', 'W', 'W' },
{ 'W', 'L', 'W', 'W', 'L' },
{ 'L', 'W', 'W', 'L', 'L' },
{ 'W', 'W', 'W', 'W', 'W' },
{ 'L', 'W', 'L', 'L', 'W' }
};
Console.WriteLine(countIslands(grid));
}
}