-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumberOfIslands.py
59 lines (48 loc) · 1.58 KB
/
NumberOfIslands.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
from collections import deque
class Queue:
def __init__(self):
self.items = deque()
def is_empty(self):
return not self.items
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
return self.items.popleft()
class Solution:
def is_valid(self,grid, row, col):
rows = len(grid)
cols = len(grid[0])
return 0 <= row < rows and 0 <= col < cols and grid[row][col] == '1'
def bfs(self, grid, row,col):
directions = [
(0,1), # right
(0,-1), # left
(-1,0), # up
(1,0), # down
]
q = Queue()
q.enqueue((row,col))
grid[row][col] = '0'
while not q.is_empty():
curr_row, curr_col = q.dequeue()
for i,j in directions:
new_row = i + curr_row
new_col = j + curr_col
#! if the new offset is '1' (valid) and unvisited
if self.is_valid(grid, new_row, new_col):
q.enqueue((new_row, new_col))
grid[new_row][new_col] = '0' #* end of bfs
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
rows = len(grid)
cols = len(grid[0])
islands = 0
for i in range(rows):
for j in range(cols):
if grid[i][j] == "1":
islands = islands+1
self.bfs(grid, i, j)
return islands
if __name__ == "__main__":
s = Solution()