小根堆

image.png
image.png
image.png

  • 堆中不重复放(就是原矩阵中之前已经放进过堆的,不再重复放)

image.png

  1. // 放入堆中的节点
  2. public static class Node {
  3. public int value;
  4. public int row;
  5. public int col;
  6. public Node(int value, int row, int col) {
  7. this.value = value;
  8. this.row = row;
  9. this.col = col;
  10. }
  11. }
  12. // 小根堆
  13. public static class NodeComparator implements Comparator<Node> {
  14. @Override
  15. public int compare(Node o1, Node o2) {
  16. return o1.value - o2.value;
  17. }
  18. }
  19. public int kthSmallest(int[][] matrix, int k) {
  20. int N = matrix.length;
  21. int M = matrix[0].length;
  22. PriorityQueue<Node> heap = new PriorityQueue<>(new NodeComparator());
  23. boolean[][] set = new boolean[N][M];
  24. //左上角的值是最小的
  25. heap.add(new Node(matrix[0][0], 0, 0));
  26. set[0][0] = true;
  27. int count = 0;
  28. Node ans = null;
  29. while (!heap.isEmpty()) {
  30. ans = heap.poll();
  31. if (++count == k) {
  32. break;
  33. }
  34. int row = ans.row;
  35. int col = ans.col;
  36. if (row + 1 < N && !set[row + 1][col]) {
  37. heap.add(new Node(matrix[row + 1][col], row + 1, col));
  38. set[row + 1][col] = true;
  39. }
  40. if (col + 1 < M && !set[row][col + 1]) {
  41. heap.add(new Node(matrix[row][col + 1], row, col + 1));
  42. }
  43. }
  44. return ans.value;
  45. }