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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxDistance ( vector < vector < int > > & grid ) { vector < pair < int , int > > one ; int M = grid . size ( ) ; int N = grid [ 0 ] . size ( ) ; int ans = -1 ; for ( int i = 0 ; i < M ; ++ i ) { for ( int j = 0 ; j < N ; ++ j ) { if ( grid [ i ] [ j ] == 1 ) one . emplace_back ( i , j ) ; } } if ( one . empty ( ) || 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 = INT_MAX ; for ( auto & p : one ) { int d = abs ( p . first - i ) + abs ( p . second - j ) ; dist = min ( dist , d ) ; if ( dist <= ans ) break ; } ans = max ( ans , dist ) ; } } return ans ; } int main ( ) { vector < vector < int > > arr = { { 0 , 0 , 1 } , { 0 , 0 , 0 } , { 0 , 0 , 0 } } ; cout << maxDistance ( arr ) << endl ; return 0 ; }