Skip to content

Commit 5be6e9f

Browse files
author
weiy
committed
number of islands medium
1 parent ac9fec8 commit 5be6e9f

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

Array/NumberOfIslands.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
"""
2+
与今日头条的秋招第一题差不多的题:
3+
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
4+
5+
Example 1:
6+
7+
Input:
8+
11110
9+
11010
10+
11000
11+
00000
12+
13+
Output: 1
14+
Example 2:
15+
16+
Input:
17+
11000
18+
11000
19+
00100
20+
00011
21+
22+
Output: 3
23+
24+
分析看 FootbalFans.py
25+
26+
passed.
27+
28+
测试地址:
29+
https://leetcode.com/problems/number-of-islands/description/
30+
31+
"""
32+
class Solution(object):
33+
def makeXY(self, x, y):
34+
return ((x, y-1),
35+
(x, y+1),
36+
(x-1, y),
37+
(x+1, y))
38+
39+
def numIslands(self, court):
40+
"""
41+
:type grid: List[List[str]]
42+
:rtype: int
43+
"""
44+
fans_groups = []
45+
x = 0
46+
y = 0
47+
if not court:
48+
return 0
49+
50+
x_length = len(court[0])
51+
y_length = len(court)
52+
53+
def helper(x, y):
54+
Xy = self.makeXY(x, y)
55+
for i in Xy:
56+
try:
57+
if i[1] < 0 or i[0] < 0:
58+
continue
59+
60+
if court[i[1]][i[0]] == '1':
61+
court[i[1]][i[0]] = '0'
62+
t = helper(i[0], i[1])
63+
except IndexError:
64+
continue
65+
else:
66+
return 1
67+
68+
69+
for y in range(y_length):
70+
for x in range(x_length):
71+
if court[y][x] == '1':
72+
court[y][x] = '0'
73+
fans_groups.append(helper(x, y))
74+
75+
76+
77+
if not fans_groups:
78+
return 0
79+
80+
return len(fans_groups)
81+

0 commit comments

Comments
 (0)