Skip to content

Commit c87f1ff

Browse files
author
weiy
committed
max area of island
1 parent a23d3e1 commit c87f1ff

File tree

2 files changed

+80
-1
lines changed

2 files changed

+80
-1
lines changed

Diff for: Array/FootballFans.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
1212
类似算法的 leetcode:
1313
https://leetcode.com/problems/number-of-islands/description/ 解答请看 NumberOfIslands.py
14-
https://leetcode.com/problems/max-area-of-island/description/ 解答请看
14+
https://leetcode.com/problems/max-area-of-island/description/ 解答请看 MaxAreaOfIsland.py
1515
1616
"""
1717

Diff for: Array/MaxAreaOfIsland.py

+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
"""
2+
与今日头条秋招第一题最相似的一道题,只是方向少了四个。
3+
4+
Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
5+
6+
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
7+
8+
Example 1:
9+
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
10+
[0,0,0,0,0,0,0,1,1,1,0,0,0],
11+
[0,1,1,0,1,0,0,0,0,0,0,0,0],
12+
[0,1,0,0,1,1,0,0,1,0,1,0,0],
13+
[0,1,0,0,1,1,0,0,1,1,1,0,0],
14+
[0,0,0,0,0,0,0,0,0,0,1,0,0],
15+
[0,0,0,0,0,0,0,1,1,1,0,0,0],
16+
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
17+
Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.
18+
Example 2:
19+
[[0,0,0,0,0,0,0,0]]
20+
Given the above grid, return 0.
21+
Note: The length of each dimension in the given grid does not exceed 50.
22+
23+
passed:
24+
beat 54%.
25+
26+
测试地址:
27+
https://leetcode.com/problems/max-area-of-island/description/
28+
29+
"""
30+
31+
class Solution(object):
32+
def makeAroundXY(self, x, y):
33+
return ((x, y-1),
34+
(x, y+1),
35+
(x-1, y),
36+
(x+1, y))
37+
38+
def maxAreaOfIsland(self, court):
39+
"""
40+
:type grid: List[List[str]]
41+
:rtype: int
42+
"""
43+
fans_groups = []
44+
x = 0
45+
y = 0
46+
if not court:
47+
return 0
48+
49+
x_length = len(court[0])
50+
y_length = len(court)
51+
52+
def helper(x, y, result=0):
53+
Xy = self.makeAroundXY(x, y)
54+
for i in Xy:
55+
try:
56+
if i[0] < 0 or i[1] < 0:
57+
continue
58+
59+
if court[i[1]][i[0]] == 1:
60+
court[i[1]][i[0]] = 0
61+
result += 1
62+
t = helper(i[0], i[1], 0)
63+
result += t
64+
except IndexError:
65+
continue
66+
else:
67+
return result
68+
69+
70+
for y in range(y_length):
71+
for x in range(x_length):
72+
if court[y][x] == 1:
73+
court[y][x] = 0
74+
fans_groups.append(helper(x, y, 1))
75+
76+
if not fans_groups:
77+
return 0
78+
79+
return max(fans_groups)

0 commit comments

Comments
 (0)