Find the Kth Smallest Sum of a Matrix With Sorted Rows LeetCode solution in Python
1class Solution:2def kthSmallest(self, mat: List[List[int]], k: int) -> int:3def kSmallestPairs(4nums1: List[int], nums2: List[int], k: int5) -> List[List[int]]:6h = [(nums1[0] + nums2[0], 0, 0)]7visited = set()8res = []9while h and k > 0:10e, i, j = heappop(h)11if (i, j) in visited:12continue13res.append(e)14visited.add((i, j))15if j + 1 < len(nums2):16heappush(h, (nums1[i] + nums2[j + 1], i, j + 1))17if i + 1 < len(nums1):18heappush(h, (nums1[i + 1] + nums2[j], i + 1, j))19k -= 120return res2122res = mat[0]23for i in range(1, len(mat)):24res = kSmallestPairs(res, mat[i], k)25return res[-1]