原题链接
解题思路
这道题用BFS+优先级队列(堆)。其实这道题和我前面写的一道题解题方法一模一样。题号是373。这里就不细讲了。
解题代码
public class Solution {
public int kthSmallest(int[][] matrix, int k) {
PriorityQueue<Num> q = new PriorityQueue<>();
int n = matrix.length;
int count = 0;
int res = 0;
q.offer(new Num(0,0,matrix[0][0]));
boolean[][] visited = new boolean[n][n];
visited[0][0] = true;
while(!q.isEmpty()) {
Num num = q.poll();
if(++count == k) {
return num.val;
}
if(num.x + 1 < n && !visited[num.x + 1][num.y]) {
Num tnum = new Num(num.x + 1,num.y,matrix[num.x + 1][num.y]);
q.offer(tnum);
visited[num.x + 1][num.y] = true;
}
if(num.y + 1 < n && !visited[num.x][num.y + 1]) {
Num tnum = new Num(num.x,num.y + 1,matrix[num.x][num.y + 1]);
q.offer(tnum);
visited[num.x][num.y + 1] = true;
}
}
return -1;
}
}
class Num implements Comparable<Num>{
int x;
int y;
int val;
Num(int x,int y,int val) {
this.x = x;
this.y = y;
this.val = val;
}
@Override
public int compareTo(Num o) {
return this.val - o.val;
}
}