```
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int rowcnt = matrix.size();
int colcnt = matrix[0].size();
vector<int> curidx(rowcnt, 0);
int res;
for (int i = 0; i < k; ++i) {
int rr = -1;
int rres = INT_MAX;
for (int r = 0; r < rowcnt; ++r) {
if (curidx[r] < colcnt && matrix[r][curidx[r]] < rres) {
rres = matrix[r][curidx[r]];
rr = r;
}
}
if (rr != -1) {
curidx[rr] += 1;
res = rres;
}
}
return res;
}
};
```