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 ; Function to find the maximum distance ; Queue to store all 1 - cells ; Grid dimensions ; Directions traversable from a given a particular cell ; If the grid contains only 0 s or only 1 s ; Access every 1 - cell ; Traverse all possible directions from the cells ; Check if the cell is within the boundaries or contains a 1 ; Driver code
using System ; using System . Collections . Generic ; class GFG { static int index = 0 ; class pair { public int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int maxDistance ( int [ , ] grid ) { Queue < pair > q = new Queue < pair > ( ) ; int M = grid . GetLength ( 0 ) ; int N = grid . GetLength ( 1 ) ; int ans = - 1 ; int [ , ] dirs = { { 0 , 1 } , { 1 , 0 } , { 0 , - 1 } , { - 1 , 0 } } ; for ( int i = 0 ; i < M ; ++ i ) { for ( int j = 0 ; j < N ; ++ j ) { if ( grid [ i , j ] == 1 ) q . Enqueue ( new pair ( i , j ) ) ; } } if ( q . Count == 0 M * N == q . Count ) return - 1 ; while ( q . Count > 0 ) { int cnt = q . Count ; while ( cnt -- > 0 ) { pair p = q . Peek ( ) ; q . Dequeue ( ) ; for ( int i = 0 ; i < dirs . GetLength ( 0 ) ; ) { int [ ] dir = GetRow ( dirs , i ++ ) ; int x = p . first + dir [ 0 ] ; int y = p . second + dir [ 1 ] ; if ( x < 0 x >= M y < 0 y >= N grid [ x , y ] > 0 ) continue ; q . Enqueue ( new pair ( x , y ) ) ; grid [ x , y ] = 1 ; } } ++ ans ; } return ans ; } public static int [ ] GetRow ( int [ , ] matrix , int row ) { var rowLength = matrix . GetLength ( 1 ) ; var rowVector = new int [ rowLength ] ; for ( var i = 0 ; i < rowLength ; i ++ ) rowVector [ i ] = matrix [ row , i ] ; return rowVector ; } public static void Main ( String [ ] args ) { int [ , ] arr = { { 0 , 0 , 1 } , { 0 , 0 , 0 } , { 0 , 0 , 1 } } ; Console . Write ( maxDistance ( arr ) + " STRNEWLINE " ) ; } }