Count all sorted rows in a matrix | Function to count all sorted rows in a matrix ; Initialize result ; Start from left side of matrix to count increasing order rows ; Check if there is any pair ofs element that are not in increasing order . ; If the loop didn 't break (All elements of current row were in increasing order) ; Start from right side of matrix to count increasing order rows ( reference to left these are in decreasing order ) ; Check if there is any pair ofs element that are not in decreasing order . ; Note c > 1 condition is required to make sure that a single column row is not counted twice ( Note that a single column row is sorted both in increasing and decreasing order ) ; Driver code
def sortedCount ( mat , r , c ) : NEW_LINE INDENT result = 0 NEW_LINE for i in range ( r ) : NEW_LINE INDENT j = 0 NEW_LINE for j in range ( c - 1 ) : NEW_LINE INDENT if mat [ i ] [ j + 1 ] <= mat [ i ] [ j ] : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if j == c - 2 : NEW_LINE INDENT result += 1 NEW_LINE DEDENT DEDENT for i in range ( 0 , r ) : NEW_LINE INDENT j = 0 NEW_LINE for j in range ( c - 1 , 0 , - 1 ) : NEW_LINE INDENT if mat [ i ] [ j - 1 ] <= mat [ i ] [ j ] : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if c > 1 and j == 1 : NEW_LINE INDENT result += 1 NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT m , n = 4 , 5 NEW_LINE mat = [ [ 1 , 2 , 3 , 4 , 5 ] , [ 4 , 3 , 1 , 2 , 6 ] , [ 8 , 7 , 6 , 5 , 4 ] , [ 5 , 7 , 8 , 9 , 10 ] ] NEW_LINE print ( sortedCount ( mat , m , n ) ) NEW_LINE