using System;
using System.Collections.Generic;
class GFG {
public static bool check(int i, int j, int n, int m)
{
return i >= 0 && j >= 0 && i < n && j < m;
}
public static void mark_component(List<List<int> > v,
List<List<bool> > vis,
int i, int j)
{
int n = v.Count;
int m = v[0].Count;
if (!check(i, j, n, m))
return;
vis[i][j] = true;
if (v[i][j] == 1) {
v[i][j] = 0;
mark_component(v, vis, i + 1, j);
mark_component(v, vis, i - 1, j);
mark_component(v, vis, i, j + 1);
mark_component(v, vis, i, j - 1);
mark_component(v, vis, i + 1, j + 1);
mark_component(v, vis, i - 1, j - 1);
mark_component(v, vis, i + 1, j - 1);
mark_component(v, vis, i - 1, j + 1);
}
}
public static void Main()
{
List<List<int> > v = new List<List<int> >{
new List<int>{ 1, 1, 0, 0, 0 },
new List<int>{ 0, 1, 0, 0, 1 },
new List<int>{ 1, 0, 0, 1, 1 },
new List<int>{ 0, 0, 0, 0, 0 },
new List<int>{ 1, 0, 1, 0, 1 }
};
int n = v.Count;
int m = v[0].Count;
int cnt = 0;
List<List<bool> > vis = new List<List<bool> >();
for (int i = 0; i < n; i++) {
vis.Add(new List<bool>());
for (int j = 0; j < m; j++) {
vis[i].Add(false);
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (!vis[i][j] && v[i][j] == 1) {
cnt++;
mark_component(v, vis, i, j);
}
}
}
Console.WriteLine(
"The number of islands in the matrix are :");
Console.WriteLine(cnt);
}
}