4.Kth Smallest Element in a Sorted Matrix
Example:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
return 13.Solution:

Last updated
Example:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
return 13.
Last updated
class Solution
{
public:
int kthSmallest(vector<vector<int>> &matrix, int k)
{
int n = matrix.size();
set<pair<int, int>> s;
priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<pair<int, pair<int, int>>>> pq;
pq.push({matrix[0][0], {0, 0}});
s.insert({0, 0});
int i = 1;
while (i < k)
{
int ele = pq.top().first;
int idx1 = pq.top().second.first;
int idx2 = pq.top().second.second;
pq.pop();
if (idx1 + 1 < n)
{
if (s.find({idx1 + 1, idx2}) == s.end())
{
pq.push({matrix[idx1 + 1][idx2], {idx1 + 1, idx2}});
s.insert({idx1 + 1, idx2});
}
}
if (idx2 + 1 < n )
{
if (s.find({idx1, idx2 + 1}) == s.end())
{
pq.push({matrix[idx1][idx2 + 1], {idx1, idx2 + 1}});
s.insert({idx1, idx2 + 1});
}
}
i++;
}
return pq.top().first;
}
};