K-th smallest number in sorted matrix

problem [https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/ 378. Kth Smallest Element in a Sorted Matrix].

Problem description
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.


 * Example


 * Note
 * You may assume k is always valid, 1 ≤ k ≤ n2.

Analysis
One trick we can use is Manhattan distance.


 * Manhattan distance
 * For two elements A[row1][col1] and A[row2][col2], The Manhattan distance between the two elements = |row1 - row2| + |col1 - col2|.

Since we know that the top-left element (A[0][0]) is the 1st smallest element, then we know that k-th smallest element must have Manhattan distance &le; k-1 from the top-left element.


 * Illustration
 * k = 4, i.e. find the 4th smallest element.
 * {| border="1" style="border-collapse: collapse; width: 200px; table-layout: fixed; text-align: center;"


 * style="background-color: lightgray;" | 1 || style="background-color: yellow;" | 2 || style="background-color: lime;" | 3 || style="background-color: yellow;" | 4 || 5
 * style="background-color: yellow;" | 2 || style="background-color: yellow;" | 4 || style="background-color: yellow;" | 5 || 8 || 9
 * style="background-color: yellow;" | 4 || style="background-color: yellow;" | 5 || 10 || 12 || 13
 * style="background-color: yellow;" | 6 || 8 || 11 || 13 || 17
 * 7 || 9 || 13 || 17 || 20
 * }
 * Lightgray color : top-left element.
 * Yellow color : elements that have Manhattan distance &le; 4 - 1 = 3 from the top-left element.
 * Lime color : correct result.
 * 7 || 9 || 13 || 17 || 20
 * }
 * Lightgray color : top-left element.
 * Yellow color : elements that have Manhattan distance &le; 4 - 1 = 3 from the top-left element.
 * Lime color : correct result.

Based on the illustration above, we only need to push in the elements in the top-left triangle into a min-heap.

Then we pop from the min-heap k times to get the desired result.

Time complexity

 * 1) The top-left triangle that we use to build the heap has $$k^2 / 2$$ elements. So the time complexity of extracting these elements is O(k2).
 * 2) Building the min-heap has time complexity O(k2 log k2).
 * 3) Popping off from the min-heap has time complexity O(k log k2).

So total time complexity is O(k2 log k2).

Space complexity

 * Stack
 * Since we do not have recursion here, the stack space complexity is O(1).


 * Heap
 * Our auxiliary object is the min-heap, which has at most $$k^2 / 2$$ elements. So the heap space complexity is O(k2).

So the total space complexity is O(k2).

C++

 * 
 * To construct a min-heap, the comparison type is.
 * The full declaration of a min-heap would be

Java

 * class