GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/python/695_Max_Area_of_Island.py at master · qiyuangong/leetcode

Expand file tree

/

695_Max_Area_of_Island.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
67 lines (63 loc) · 2.22 KB
/

695_Max_Area_of_Island.py

Copy path

File metadata and controls

67 lines (63 loc) · 2.22 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
class Solution(object):
def maxAreaOfIsland(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
# because
ans = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
grid[i][j] = 0
ans = max(self.dfs(grid, i, j), ans)
# ans = max(self.bfs(grid, i, j), ans)
return ans
def dfs(self, grid, i, j):
# DFS based on stack
stack = [(i, j)]
area = 0
# Stack for DFS
while stack:
r, c = stack.pop(-1)
area += 1
for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
if (0 <= nr < len(grid) and
0 <= nc < len(grid[0]) and grid[nr][nc]):
stack.append((nr, nc))
grid[nr][nc] = 0
return area
# def bfs(self, grid, x, y):
# # BFS based on queue
# queue = [(x, y)]
# area = 0
# # Stack for DFS
# while queue:
# i, j = queue.pop(0)
# area += 1
# if i - 1 >= 0 and grid[i - 1][j] == 1:
# grid[i - 1][j] = 0
# queue.append((i - 1, j))
# if i + 1 < len(grid) and grid[i + 1][j] == 1:
# grid[i + 1][j] = 0
# queue.append((i + 1, j))
# if j - 1 >= 0 and grid[i][j - 1] == 1:
# grid[i][j - 1] = 0
# queue.append((i, j - 1))
# if j + 1 < len(grid[0]) and grid[i][j + 1] == 1:
# grid[i][j + 1] = 0
# queue.append((i, j + 1))
# return area
# def maxAreaOfIsland(self, grid):
# # Recursive DFS
# seen = set()
# def area(r, c):
# if not (0 <= r < len(grid) and 0 <= c < len(grid[0])
# and (r, c) not in seen and grid[r][c]):
# return 0
# seen.add((r, c))
# return (1 + area(r+1, c) + area(r-1, c) +
# area(r, c-1) + area(r, c+1))
# return max(area(r, c)
# for r in range(len(grid))
# for c in range(len(grid[0])))
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.