forked from yingl/LintCodeInPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimum_path_sum.py
More file actions
25 lines (23 loc) · 942 Bytes
/
minimum_path_sum.py
File metadata and controls
25 lines (23 loc) · 942 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# -*- coding: utf-8 -*-
class Solution:
"""
@param grid: a list of lists of integers.
@return: An integer, minimizes the sum of all numbers along its path
"""
def minPathSum(self, grid):
# write your code here
rows, cols = len(grid), len(grid[0])
self.min_paths = [[-1] * cols for row in xrange(rows)]
self.min_paths[0][0] = grid[0][0]
return self.dfs(grid, rows - 1, cols - 1)
def dfs(self, grid, row, col):
if self.min_paths[row][col] >= 0:
return self.min_paths[row][col]
if (row >= 1) and (col >= 1):
dist = grid[row][col] + min(self.dfs(grid, row - 1, col), self.dfs(grid, row, col - 1))
elif row >= 1:
dist = grid[row][col] + self.dfs(grid, row - 1, col)
elif col >= 1:
dist = grid[row][col] + self.dfs(grid, row, col - 1)
self.min_paths[row][col] = dist
return dist