using
System;
using
System.Collections.Generic;
class
GFG {
static
bool
isValid(
int
[,] screen,
int
m,
int
n,
int
x,
int
y,
int
prevC,
int
newC)
{
if
(x < 0 || x >= m || y < 0 || y >= n || screen[x, y] != prevC
|| screen[x,y]== newC)
return
false
;
return
true
;
}
static
void
floodFill(
int
[,] screen,
int
m,
int
n,
int
x,
int
y,
int
prevC,
int
newC)
{
List<Tuple<
int
,
int
>> queue =
new
List<Tuple<
int
,
int
>>();
queue.Add(
new
Tuple<
int
,
int
>(x, y));
screen[x,y] = newC;
while
(queue.Count > 0)
{
Tuple<
int
,
int
> currPixel = queue[queue.Count - 1];
queue.RemoveAt(queue.Count - 1);
int
posX = currPixel.Item1;
int
posY = currPixel.Item2;
if
(isValid(screen, m, n, posX + 1, posY, prevC, newC))
{
screen[posX + 1,posY] = newC;
queue.Add(
new
Tuple<
int
,
int
>(posX + 1, posY));
}
if
(isValid(screen, m, n, posX-1, posY, prevC, newC))
{
screen[posX-1,posY]= newC;
queue.Add(
new
Tuple<
int
,
int
>(posX-1, posY));
}
if
(isValid(screen, m, n, posX, posY + 1, prevC, newC))
{
screen[posX,posY + 1]= newC;
queue.Add(
new
Tuple<
int
,
int
>(posX, posY + 1));
}
if
(isValid(screen, m, n, posX, posY-1, prevC, newC))
{
screen[posX,posY-1]= newC;
queue.Add(
new
Tuple<
int
,
int
>(posX, posY-1));
}
}
}
static
void
Main() {
int
[,] screen ={
{1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 0, 0},
{1, 0, 0, 1, 1, 0, 1, 1},
{1, 2, 2, 2, 2, 0, 1, 0},
{1, 1, 1, 2, 2, 0, 1, 0},
{1, 1, 1, 2, 2, 2, 2, 0},
{1, 1, 1, 1, 1, 2, 1, 1},
{1, 1, 1, 1, 1, 2, 2, 1}};
int
m = screen.GetLength(0);
int
n = screen.GetLength(1);
int
x = 4;
int
y = 4;
int
prevC = screen[x,y];
int
newC = 3;
floodFill(screen, m, n, x, y, prevC, newC);
for
(
int
i = 0; i < m; i++)
{
for
(
int
j = 0; j < n; j++)
{
Console.Write(screen[i,j] +
" "
);
}
Console.WriteLine();
}
}
}