forked from Azureki/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlc200. Number of Islands.py
47 lines (40 loc) · 1.32 KB
/
lc200. Number of Islands.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
import queue
class Solution:
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
if not grid:
return 0
res = 0
length = len(grid)
length0 = len(grid[0])
q = queue.Queue()
visited = [[0] * length0 for i in range(length)]
for i in range(length):
for j in range(length0):
if not visited[i][j] and grid[i][j] == '1':
q.put((i, j))
res += 1
while not q.empty():
isl = q.get()
if isl[0] < 0 or isl[0] >= length:
continue
if isl[1] < 0 or isl[1] >= length0:
continue
if not visited[isl[0]][isl[1]] and grid[isl[0]][isl[1]] == '1':
visited[isl[0]][isl[1]] = 1
q.put((isl[0] - 1, isl[1]))
q.put((isl[0] + 1, isl[1]))
q.put((isl[0], isl[1] - 1))
q.put((isl[0], isl[1] + 1))
return res
snum = '''11000
11000
00100
00011'''
slst = snum.split('\n')
grid = [[int(x) for x in list(s)] for s in slst]
soln = Solution()
print(soln.numIslands(slst))