Maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix | Java 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
import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int maxDistance ( int [ ] [ ] grid ) { Vector < pair > one = new Vector < pair > ( ) ; int M = grid . length ; int N = grid [ 0 ] . length ; 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 . isEmpty ( ) || M * N == one . size ( ) ) return - 1 ; for ( int i = 0 ; i < M ; ++ i ) { for ( int j = 0 ; j < N ; ++ j ) { if ( grid [ i ] [ j ] == 1 ) continue ; int dist = Integer . MAX_VALUE ; for ( pair p : 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 } } ; System . out . print ( maxDistance ( arr ) + "NEW_LINE"); } }