给定一个 nxn 矩阵,其中每一行和每一列都按非降序排序。按排序顺序打印矩阵的所有元素。
例子:
Input : mat= [[10, 20, 30, 40],
[15, 25, 35, 45],
[27, 29, 37, 48],
[32, 33, 39, 50]]
Output : Elements of matrix in sorted order
[10, 15, 20, 25, 27, 29, 30, 32,
33, 35, 37, 39, 40, 45, 48, 50]
此问题已有解决方案,请参阅链接。我们将在Python使用heapq 模块合并两个排序数组的相同方法来解决这个问题。
# Function to print all elements in sorted order
# from row and column wise sorted matrix
from heapq import merge
def sortedMatrix(mat):
# initialize result variable with first row of matrix
result=mat[0]
# now traverse through complete matrix
# after first row and merge each row with
# result one by one
# after last operation result will contain
# list of sorted elements of matrix
for row in mat[1:]:
result=list(merge(result,row))
return result
if __name__ == "__main__":
mat = [[10, 20, 30, 40],
[15, 25, 35, 45],
[27, 29, 37, 48],
[32, 33, 39, 50]]
print ('Elements of matrix in sorted order')
print (sortedMatrix(mat))
输出:
Elements of matrix in sorted order
[10, 15, 20, 25, 27, 29, 30, 32, 33, 35, 37, 39, 40, 45, 48, 50]
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。