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
def countIslands ( mat ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( 0 , M ) : NEW_LINE INDENT for j in range ( 0 , N ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == ' X ' ) : NEW_LINE INDENT if ( ( i == 0 or mat [ i - 1 ] [ j ] == ' O ' ) and ( j == 0 or mat [ i ] [ j - 1 ] == ' O ' ) ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return count NEW_LINE DEDENT M = 6 NEW_LINE N = 3 NEW_LINE mat = [ [ ' O ' , ' O ' , ' O ' ] , [ ' X ' , ' X ' , ' O ' ] , [ ' X ' , ' X ' , ' O ' ] , [ ' O ' , ' O ' , ' X ' ] , [ ' O ' , ' O ' , ' X ' ] , [ ' X ' , ' X ' , ' O ' ] ] NEW_LINE print ( " Number ▁ of ▁ rectangular ▁ islands ▁ is " , countIslands ( mat ) ) NEW_LINE