forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-number-of-fish-in-a-grid.py
71 lines (66 loc) · 2.08 KB
/
maximum-number-of-fish-in-a-grid.py
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# Time: O(m * n)
# Space: O(m + n)
# bfs
class Solution(object):
def findMaxFish(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1))
def bfs(i, j):
result = grid[i][j]
grid[i][j] = 0
q = [(i, j)]
while q:
new_q = []
for i, j in q:
for di, dj in DIRECTIONS:
ni, nj = i+di, j+dj
if not (0 <= ni < len(grid) and
0 <= nj < len(grid[0]) and
grid[ni][nj]):
continue
result += grid[ni][nj]
grid[ni][nj] = 0
new_q.append((ni, nj))
q = new_q
return result
result = 0
for i in xrange(len(grid)):
for j in xrange(len(grid[0])):
if grid[i][j]:
result = max(result, bfs(i, j))
return result
# Time: O(m * n)
# Space: O(m * n)
# dfs
class Solution2(object):
def findMaxFish(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1))
def dfs(i, j):
result = grid[i][j]
grid[i][j] = 0
stk = [(i, j)]
while stk:
i, j = stk.pop()
for di, dj in reversed(DIRECTIONS):
ni, nj = i+di, j+dj
if not (0 <= ni < len(grid) and
0 <= nj < len(grid[0]) and
grid[ni][nj]):
continue
result += grid[ni][nj]
grid[ni][nj] = 0
stk.append((ni, nj))
return result
result = 0
for i in xrange(len(grid)):
for j in xrange(len(grid[0])):
if grid[i][j]:
result = max(result, dfs(i, j))
return result