using
System;
using
System.Collections.Generic;
public
class
GFG
{
static
readonly
int
M = 3;
static
readonly
int
N = 3;
class
pair
{
public
int
first, second;
public
pair(
int
first,
int
second)
{
this
.first = first;
this
.second = second;
}
}
static
void
findHeightMatrixUtil(
int
[,]mat,
int
[,]height)
{
Queue<pair > q =
new
Queue<pair>();
int
[,]vis =
new
int
[M,N];
for
(
int
i = 0; i < M; i++) {
for
(
int
j = 0; j < N; j++) {
if
(mat[i,j] == 1) {
q.Enqueue(
new
pair( i, j ));
height[i,j] = 0;
vis[i,j] = 1;
}
}
}
while
(q.Count != 0 )
{
pair k = q.Peek();
q.Dequeue();
int
x = k.first, y = k.second;
if
(x > 0 && vis[x - 1, y] == 0) {
height[x - 1, y] = height[x, y] + 1;
vis[x - 1, y] = 1;
q.Enqueue(
new
pair( x - 1, y ));
}
if
(y > 0 && vis[x, y - 1] == 0) {
height[x, y - 1] = height[x, y] + 1;
vis[x, y - 1] = 1;
q.Enqueue(
new
pair( x, y - 1 ));
}
if
(x < M - 1 && vis[x + 1, y] == 0) {
height[x + 1, y] = height[x, y] + 1;
vis[x + 1, y] = 1;
q.Enqueue(
new
pair( x + 1, y ));
}
if
(y < N - 1 && vis[x, y + 1] == 0) {
height[x, y + 1] = height[x, y] + 1;
vis[x, y + 1] = 1;
q.Enqueue(
new
pair( x, y + 1 ));
}
}
}
static
void
findHeightMatrix(
int
[,]mat)
{
int
[,]height =
new
int
[M, N];
findHeightMatrixUtil(mat, height);
for
(
int
i = 0; i < M; i++) {
for
(
int
j = 0; j < N; j++)
Console.Write(height[i,j]+
" "
);
Console.WriteLine();
}
}
public
static
void
Main(String[] args)
{
int
[,]mat
= { { 0, 0,0 }, { 0, 1,0 },{ 0, 0,0 } };
findHeightMatrix(mat);
}
}