|
| 1 | +import sys |
| 2 | + |
| 3 | +# 1. Express a solution mathematically: Let's be a Matrix M of (n+1) x (m+1): |
| 4 | +# For 0 <= r <= n and 0 <= c <= m, M[r,c] contains the longest path from the source (0, 0) to (r, c) |
| 5 | +# M[0 , 0] = 0 |
| 6 | +# M[0 , c] = M[0 , c - 1] + right[0, c] for 1 <= c <= m |
| 7 | +# M[r , 0] = M[r - 1 , 0] + down[r , 0] for 1 <= r <= n |
| 8 | +# M[r , c] = max(M[r - 1 , c] + down[r - 1 , c], M[r , c - 1] + right[r , c - 1]) |
| 9 | +# 2. Proof: |
| 10 | +# Let's assume that there is a vertice (r, c) that belongs to the optimal path P with a the longest path length |P| |
| 11 | +# But M[r , c] < max(M[r - 1 , c] + down[r - 1 , c], M[r , c - 1] + right[r , c - 1]) |
| 12 | +# This means that if we replace M[r , c] with max(M[r - 1 , c] + down[r - 1 , c], M[r , c - 1] + right[r , c - 1]) |
| 13 | +# The new path P length |P'| will be greater than |P| ==> contradiction with the fact that |P| was the longest path |
| 14 | +# 3. Implementation: |
| 15 | +# Buttom up solution |
| 16 | +# Running Time: O(nm) (Quadratic) |
| 17 | +# Space complexity: O(nm) (Quadratic) |
| 18 | +class Solution: |
| 19 | + def __init__(self, n, m): |
| 20 | + self.rows_count = n + 1 |
| 21 | + self.columns_count = m + 1 |
| 22 | + |
| 23 | + def longest_path(self, down, right): |
| 24 | + |
| 25 | + M = [ [0 for _ in range(self.columns_count)] for _ in range(self.rows_count) ] |
| 26 | + |
| 27 | + for c in range(1, self.columns_count, 1): |
| 28 | + M[0][c] = M[0][c - 1] + right[0][c - 1] |
| 29 | + |
| 30 | + for r in range(1, self.rows_count, 1): |
| 31 | + M[r][0] = M[r - 1][0] + down[r - 1][0] |
| 32 | + |
| 33 | + for r in range(1, self.rows_count, 1): |
| 34 | + for c in range(1, self.columns_count, 1): |
| 35 | + candidate_predecesor_top = M[r - 1][c] + down[r - 1][c] |
| 36 | + candidate_predecesor_left = M[r][c - 1] + right[r][c - 1] |
| 37 | + M[r][c] = max(candidate_predecesor_top, candidate_predecesor_left) |
| 38 | + |
| 39 | + return M[self.rows_count - 1][self.columns_count - 1] |
| 40 | + |
| 41 | +if __name__ == "__main__": |
| 42 | + n,m = map(int, sys.stdin.readline().strip().split()) |
| 43 | + down = [list(map(int, sys.stdin.readline().strip().split())) |
| 44 | + for _ in range(n)] |
| 45 | + sys.stdin.readline() |
| 46 | + right = [list(map(int, sys.stdin.readline().strip().split())) |
| 47 | + for _ in range(n+1)] |
| 48 | + |
| 49 | + s = Solution(n, m) |
| 50 | + print(s.longest_path(down, right)) |
0 commit comments