Approach
Breadth-first search
For Find the Kth Smallest Sum of a Matrix With Sorted Rows, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 32 lines of Java from the credited upstream file 1439.java.
- The implementation visibly relies on sequence storage, work queue.
- 3 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int kthSmallest(int[][] mat, int k) {3 int[] row = mat[0];4 5 for (int i = 1; i < mat.length; ++i)6 row = kSmallestPairSums(row, mat[i], k);7 8 return row[k - 1];9 }10 11 private record T(int i, int j, int sum) {}12 13 14 private int[] kSmallestPairSums(int[] nums1, int[] nums2, int k) {15 List<Integer> ans = new ArrayList<>();16 Queue<T> minHeap = new PriorityQueue<>(Comparator.comparingInt(T::sum));17 18 for (int i = 0; i < k && i < nums1.length; ++i)19 minHeap.offer(new T(i, 0, nums1[i] + nums2[0]));20 21 while (!minHeap.isEmpty() && ans.size() < k) {22 final int i = minHeap.peek().i;23 final int j = minHeap.poll().j;24 ans.add(nums1[i] + nums2[j]);25 if (j + 1 < nums2.length)26 minHeap.offer(new T(i, j + 1, nums1[i] + nums2[j + 1]));27 }28 29 return ans.stream().mapToInt(Integer::intValue).toArray();30 }31}32