forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path378.Kth Smallest Element in a Sorted Matrix.cpp
53 lines (46 loc) · 1.22 KB
/
378.Kth Smallest Element in a Sorted Matrix.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
private:
int M;
int N;
struct cmp
{
bool operator()(pair<int,int>a,pair<int,int>b)
{
return a.first>=b.first;
}
};
public:
int kthSmallest(vector<vector<int>>& matrix, int k)
{
M=matrix.size();
N=matrix[0].size();
auto visited=vector<vector<int>>(M,vector<int>(N,0));
visited[0][0]=1;
priority_queue<pair<int,int>,vector<pair<int,int>>,cmp>q;
q.push({matrix[0][0],0});
int count=0;
int result;
while (count<k)
{
//cout<<count<<endl;
int i=q.top().second/N;
int j=q.top().second%N;
int t=q.top().first;
q.pop();
count++;
if (count==k)
result=t;
if (i+1<M && j<N && visited[i+1][j]==0)
{
q.push({matrix[i+1][j],(i+1)*N+j});
visited[i+1][j]=1;
}
if (i<M && j+1<N && visited[i][j+1]==0)
{
q.push({matrix[i][j+1],(i)*N+j+1});
visited[i][j+1]=1;
}
}
return result;
}
};