using
System;
using
System.Collections.Generic;
public
class
GFG {
public
static
int
[] p =
new
int
[100000];
public
static
int
find(
int
x)
{
if
(p[x] != x)
p[x] = find(p[x]);
return
p[x];
}
public
static
int
index(
int
x,
int
y,
int
m)
{
return
x * m + y;
}
public
static
List<
int
>
numOfIslands(
int
n,
int
m,
ref
List<List<
int
> > operators)
{
if
(operators.Count == 0) {
List<
int
> ans =
new
List<
int
>();
return
ans;
}
List<
int
> res =
new
List<
int
>();
HashSet<
int
> nodes =
new
HashSet<
int
>();
int
s = operators.Count;
HashSet<
int
> current =
new
HashSet<
int
>();
int
[] dx = { 0, 1, 0, -1 };
int
[] dy = { 1, 0, -1, 0 };
int
total = 0;
for
(
int
i = 0; i < operators.Count; i++) {
List<
int
> op = operators[i];
int
pos = index(op[0], op[1], m);
nodes.Add(pos);
if
(current.Contains(pos)) {
res.Add(total);
continue
;
}
total++;
p[pos] = pos;
for
(
int
j = 0; j < 4; j++) {
int
nx = op[0] + dx[j];
int
ny = op[1] + dy[j];
if
(!(nx >= 0 && nx < n && ny >= 0
&& ny < m))
continue
;
if
(current.Contains(index(nx, ny, m))) {
int
apos = index(op[0], op[1], m);
int
bpos = index(nx, ny, m);
if
(find(apos) != find(bpos)) {
p[find(apos)] = find(bpos);
total--;
}
}
}
current.Add(index(op[0], op[1], m));
res.Add(total);
}
return
res;
}
public
static
void
Main(
string
[] args)
{
int
N = 4, M = 5, K = 4;
List<List<
int
> > query =
new
List<List<
int
> >();
List<
int
> a1 =
new
List<
int
>();
a1.Add(1);
a1.Add(1);
query.Add(a1);
List<
int
> a2 =
new
List<
int
>();
a2.Add(0);
a2.Add(1);
query.Add(a2);
List<
int
> a3 =
new
List<
int
>();
a3.Add(3);
a3.Add(3);
query.Add(a3);
List<
int
> a4 =
new
List<
int
>();
a4.Add(3);
a4.Add(4);
query.Add(a4);
List<
int
> ans =
new
List<
int
>();
ans = numOfIslands(N, M,
ref
query);
for
(
int
i = 0; i < ans.Count; i++) {
Console.Write(ans[i] +
" "
);
}
}
}