Maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix | C # program to find the maximum distance from a 0 - cell to a 1 - cell ; If the matrix consists of only 0 ' s ▁ ▁ or ▁ only ▁ 1' s ; If it 's a 0-cell ; Calculate its distance with every 1 - cell ; Compare and store the minimum ; Compare ans store the maximum ; Driver code
using System ; using System . Collections . Generic ; class GFG { class pair { public int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int maxDistance ( int [ , ] grid ) { List < pair > one = new List < pair > ( ) ; int M = grid . GetLength ( 0 ) ; int N = grid . GetLength ( 1 ) ; int ans = - 1 ; for ( int i = 0 ; i < M ; ++ i ) { for ( int j = 0 ; j < N ; ++ j ) { if ( grid [ i , j ] == 1 ) one . Add ( new pair ( i , j ) ) ; } } if ( one . Count == 0 M * N == one . Count ) return - 1 ; for ( int i = 0 ; i < M ; ++ i ) { for ( int j = 0 ; j < N ; ++ j ) { if ( grid [ i , j ] == 1 ) continue ; int dist = int . MaxValue ; foreach ( pair p in one ) { int d = Math . Abs ( p . first - i ) + Math . Abs ( p . second - j ) ; dist = Math . Min ( dist , d ) ; if ( dist <= ans ) break ; } ans = Math . Max ( ans , dist ) ; } } return ans ; } public static void Main ( String [ ] args ) { int [ , ] arr = { { 0 , 0 , 1 } , { 0 , 0 , 0 } , { 0 , 0 , 0 } } ; Console . Write ( maxDistance ( arr ) + " STRNEWLINE " ) ; } }