Distance of nearest cell having 1 in a binary matrix | C # program to find the distance of nearest cell having 1 in a binary matrix . ; Print the distance of nearest cell having 1 for each cell . ; Initialise the answer matrix with int . MaxValue . ; For each cell ; Traversing thewhole matrix to find the minimum distance . ; If cell contain 1 , check for minimum distance . ; Printing the answer . ; Driven Program
using System ; class GFG { static int N = 3 ; static int M = 4 ; static void printDistance ( int [ , ] mat ) { int [ , ] ans = new int [ N , M ] ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < M ; j ++ ) ans [ i , j ] = int . MaxValue ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < M ; j ++ ) { for ( int k = 0 ; k < N ; k ++ ) for ( int l = 0 ; l < M ; l ++ ) { if ( mat [ k , l ] == 1 ) ans [ i , j ] = Math . Min ( ans [ i , j ] , Math . Abs ( i - k ) + Math . Abs ( j - l ) ) ; } } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) Console . Write ( ans [ i , j ] + " ▁ " ) ; Console . WriteLine ( ) ; } } public static void Main ( ) { int [ , ] mat = { { 0 , 0 , 0 , 1 } , { 0 , 0 , 1 , 1 } , { 0 , 1 , 1 , 0 } } ; printDistance ( mat ) ; } }