heapq in Python to print all elements in sorted order from row and column wise sorted matrix
Last Updated :
21 Jul, 2022
Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print all elements of matrix in sorted order. Examples:
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]
This problem has existing solution please refer link. We will solve this problem in python with the same approach of merging two sorted arrays using heapq module.
Implementation:
Python3
from heapq import merge
def sortedMatrix(mat):
result = mat[ 0 ]
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))
|
Output
Elements of matrix in sorted order
[10, 15, 20, 25, 27, 29, 30, 32, 33, 35, 37, 39, 40, 45, 48, 50]
Share your thoughts in the comments
Please Login to comment...