Skip to content

Commit f378255

Browse files
authored
Create path-with-maximum-gold.py
1 parent d924cf4 commit f378255

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Python/path-with-maximum-gold.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Time: O(m^2 * n^2)
2+
# Space: O(m * n)
3+
4+
class Solution(object):
5+
def getMaximumGold(self, grid):
6+
"""
7+
:type grid: List[List[int]]
8+
:rtype: int
9+
"""
10+
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
11+
def backtracking(grid, i, j):
12+
result = 0
13+
grid[i][j] *= -1
14+
for dx, dy in directions:
15+
ni, nj = i+dx, j+dy
16+
if not (0 <= ni < len(grid) and
17+
0 <= nj < len(grid[0]) and
18+
grid[ni][nj] > 0):
19+
continue
20+
result = max(result, backtracking(grid, ni, nj))
21+
grid[i][j] *= -1
22+
return grid[i][j] + result
23+
24+
result = 0
25+
for i in xrange(len(grid)):
26+
for j in xrange(len(grid[0])):
27+
if grid[i][j]:
28+
result = max(result, backtracking(grid, i, j))
29+
return result

0 commit comments

Comments
 (0)