If current cell is ' X ' , then check whether this is top - leftmost of a rectangle . If yes , then increment count
if ( $ mat [ $ i ] [ $ j ] == ' X ' ) { if ( ( $ i == 0 $ mat [ $ i - 1 ] [ $ j ] == ' O ' ) && ( $ j == 0 $ mat [ $ i ] [ $ j - 1 ] == ' O ' ) ) $ count ++ ; } } } return $ count ; }