using
System;
using
System.Collections.Generic;
class
GFG {
static
int
[] dRow = { -1, 0, 1, 0 };
static
int
[] dCol = { 0, 1, 0, -1 };
static
List<List<
bool
>> vis;
static
bool
isValid(
int
row,
int
col,
int
COL,
int
ROW)
{
if
(row < 0 || col < 0 || col > COL - 1 || row > ROW - 1)
return
false
;
if
(vis[row][col] ==
true
)
return
false
;
return
true
;
}
static
void
DFS_iterative(
int
[,] grid,
int
M,
int
N)
{
vis =
new
List<List<
bool
>>();
for
(
int
i = 0; i < M + 5; i++)
{
vis.Add(
new
List<
bool
>());
for
(
int
j = 0; j < N + 5; j++)
{
vis[i].Add(
false
);
}
}
List<Tuple<
int
,
int
>> st =
new
List<Tuple<
int
,
int
>>();
st.Add(
new
Tuple<
int
,
int
>(0, 0));
vis[0][0] =
true
;
while
(st.Count > 0) {
Tuple<
int
,
int
> p = st[st.Count - 1];
st.RemoveAt(st.Count - 1);
int
row = p.Item1;
int
col = p.Item2;
Console.Write(grid[row,col] +
" "
);
for
(
int
i = 0; i < 4; i++) {
int
x = row + dRow[i];
int
y = col + dCol[i];
if
(isValid(x, y, M, N)) {
st.Add(
new
Tuple<
int
,
int
>(x, y));
vis[x][y] =
true
;
}
}
}
}
static
void
Main()
{
int
[,] grid = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
int
M = 4;
int
N = 4;
DFS_iterative(grid, M, N);
}
}