forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpath-with-maximum-gold.py
More file actions
29 lines (27 loc) · 924 Bytes
/
path-with-maximum-gold.py
File metadata and controls
29 lines (27 loc) · 924 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
26
27
28
29
# Time: O(m^2 * n^2)
# Space: O(m * n)
class Solution(object):
def getMaximumGold(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
def backtracking(grid, i, j):
result = 0
grid[i][j] *= -1
for dx, dy in directions:
ni, nj = i+dx, j+dy
if not (0 <= ni < len(grid) and
0 <= nj < len(grid[0]) and
grid[ni][nj] > 0):
continue
result = max(result, backtracking(grid, ni, nj))
grid[i][j] *= -1
return grid[i][j] + result
result = 0
for i in xrange(len(grid)):
for j in xrange(len(grid[0])):
if grid[i][j]:
result = max(result, backtracking(grid, i, j))
return result