class Solution: def solve(self, matrix): n = len(matrix) fc, ft = 0, 0 sc, st = 1, 0 inf = int(1e18) for row in matrix: nfc, nft = -1, inf nsc, nst = -1, inf for i, t in enumerate(row): ct = t + (ft if i != fc else st) if ct <= nft: nsc, nst = nfc, nft nfc, nft = i, ct elif ct <= nst: nsc, nst = i, ct fc, ft = nfc, nft sc, st = nsc, nst return ft ob = Solution() matrix = [ [6, 4, 5], [3, 2, 7], [3, 4, 5], [5, 4, 4] ] print(ob.solve(matrix))