using System;
using System.Collections.Generic;
class Program
{
static int Find(List<int> hashSet, int val)
{
int parent = val;
while (parent != hashSet[parent])
{
parent = hashSet[parent];
}
return parent;
}
static void Union(List<int> hashSet, int first, int second)
{
int first_father = Find(hashSet, first);
int second_father = Find(hashSet, second);
if (first_father != second_father)
hashSet[first_father] = second_father;
}
static void Change(ref List<List<char>> matrix, int x, int y, int n, int m)
{
if (x < 0 || y < 0 || x > m - 1 || y > n - 1 || matrix[x][y] == '0')
return;
matrix[x][y] = '0';
Change(ref matrix, x + 1, y, n, m);
Change(ref matrix, x, y + 1, n, m);
Change(ref matrix, x - 1, y, n, m);
Change(ref matrix, x, y - 1, n, m);
}
static void ChangeCorner(ref List<List<char>> matrix)
{
int m = matrix.Count;
int n = matrix[0].Count;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (i * j == 0 || i == m - 1 || j == n - 1)
{
if (matrix[i][j] == '1')
{
Change(ref matrix, i, j, n, m);
}
}
}
}
}
static int NumIslands(List<List<char>> matrix)
{
if (matrix.Count == 0)
return 0;
int m = matrix.Count;
int n = matrix[0].Count;
ChangeCorner(ref matrix);
List<Tuple<int, int>> edges = new List<Tuple<int, int>>();
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (matrix[i][j] == '1')
{
int id = i * n + j;
if (j + 1 < n)
{
if (matrix[i][j + 1] == '1')
{
int right = i * n + j + 1;
edges.Add(new Tuple<int, int>(id, right));
}
}
if (i + 1 < m)
{
if (matrix[i + 1][j] == '1')
{
int down = (i + 1) * n + j;
edges.Add(new Tuple<int, int>(id, down));
}
}
}
}
}
List<int> hashSet = new List<int>(m * n);
for (int i = 0; i < m * n; i++)
{
hashSet.Add(i);
}
foreach (Tuple<int, int> edge in edges)
{
Union(hashSet, edge.Item1, edge.Item2);
}
int numComponents = 0;
for (int i = 0; i < m * n; i++)
if (matrix[i / n][i %n] == '1' && hashSet[i]==i)
numComponents++;
return numComponents;
}
public static void Main()
{
int N = 5, M = 8;
List<List<char>> matrix = new List<List<char>>() {
new List<char> { '0', '0', '0', '0', '0', '0', '0', '1' },
new List<char> { '0', '1', '1', '1', '1', '0', '0', '1' },
new List<char> { '0', '1', '0', '1', '0', '0', '0', '1' },
new List<char> { '0', '1', '1', '1', '1', '0', '1', '0' },
new List<char> { '0', '0', '0', '0', '0', '0', '0', '1' }
};
Console.WriteLine(NumIslands(matrix));
}
}