Distance of nearest cell having 1 in a binary matrix | PHP program to find distance of nearest cell having 1 in a binary matrix . ; Print the distance of nearest cell having 1 for each cell . ; Initialize the answer matrix with INT_MAX . ; For each cell ; Traversing the whole matrix to find the minimum distance . ; If cell contain 1 , check for minimum distance . ; Printing the answer . ; Driver Code
< ? php $ N = 3 ; $ M = 4 ; function printDistance ( $ mat ) { global $ N , $ M ; $ ans = array ( array ( ) ) ; for ( $ i = 0 ; $ i < $ N ; $ i ++ ) for ( $ j = 0 ; $ j < $ M ; $ j ++ ) $ ans [ $ i ] [ $ j ] = PHP_INT_MAX ; for ( $ i = 0 ; $ i < $ N ; $ i ++ ) for ( $ j = 0 ; $ j < $ M ; $ j ++ ) { for ( $ k = 0 ; $ k < $ N ; $ k ++ ) for ( $ l = 0 ; $ l < $ M ; $ l ++ ) { if ( $ mat [ $ k ] [ $ l ] == 1 ) $ ans [ $ i ] [ $ j ] = min ( $ ans [ $ i ] [ $ j ] , abs ( $ i - $ k ) + abs ( $ j - $ l ) ) ; } } for ( $ i = 0 ; $ i < $ N ; $ i ++ ) { for ( $ j = 0 ; $ j < $ M ; $ j ++ ) echo $ ans [ $ i ] [ $ j ] , " ▁ " ; echo " STRNEWLINE " ; } } $ mat = array ( array ( 0 , 0 , 0 , 1 ) , array ( 0 , 0 , 1 , 1 ) , array ( 0 , 1 , 1 , 0 ) ) ; printDistance ( $ mat ) ; ? >