Count number of islands where every island is row | This function takes a matrix of ' X ' and ' O ' and returns the number of rectangular islands of ' X ' where no two islands are row - wise or column - wise adjacent , the islands may be diagonaly adjacent ; Initialize result ; Traverse the input matrix ; If current cell is ' X ' , then check whether this is top - leftmost of a rectangle . If yes , then increment count ; Driver Code
< ? php function countIslands ( $ mat ) { $ M = 6 ; $ N = 3 ; $ count = 0 ; for ( $ i = 0 ; $ i < $ M ; $ i ++ ) { for ( $ j = 0 ; $ j < $ N ; $ j ++ ) { if ( $ mat [ $ i ] [ $ j ] == ' X ' ) { if ( ( $ i == 0 $ mat [ $ i - 1 ] [ $ j ] == ' O ' ) && ( $ j == 0 $ mat [ $ i ] [ $ j - 1 ] == ' O ' ) ) $ count ++ ; } } } return $ count ; } $ mat = array ( array ( ' O ' , ' O ' , ' O ' ) , array ( ' X ' , ' X ' , ' O ' ) , array ( ' X ' , ' X ' , ' O ' ) , array ( ' O ' , ' O ' , ' X ' ) , array ( ' O ' , ' O ' , ' X ' ) , array ( ' X ' , ' X ' , ' O ' ) ) ; echo " Number ▁ of ▁ rectangular ▁ islands ▁ is ▁ " , countIslands ( $ mat ) ; ? >