An M × N matrix of real numbers is given. Find the amount of its rows whose values of elements are sorted in ascending order.
时间: 2024-06-03 14:09:02 浏览: 87
One way to solve this problem is to iterate through each row of the matrix and check if its elements are sorted in ascending order. This can be done by comparing each element to the previous one and checking if it is greater or equal to it. If all elements satisfy this condition, then the row is sorted in ascending order. We can count the number of rows that satisfy this condition and return the result.
Here is the Python code to implement this approach:
def count_sorted_rows(matrix):
count = 0
for row in matrix:
sorted_row = True
for i in range(1, len(row)):
if row[i] < row[i-1]:
sorted_row = False
break
if sorted_row:
count += 1
return count
# Example usage:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[3, 2, 1]
]
print(count_sorted_rows(matrix)) # Output: 2
In this example, the matrix has two sorted rows: [1, 2, 3] and [4, 5, 6]. The function returns 2 as the result.
阅读全文