59 lines
2.1 KiB
Python
59 lines
2.1 KiB
Python
|
class Solution:
|
||
|
def numIslands(self, grid: List[List[str]]) -> int:
|
||
|
searched_cell = set()
|
||
|
def va(s):
|
||
|
return int(s)
|
||
|
# bfs
|
||
|
ans = 0
|
||
|
row = len(grid)
|
||
|
column = len(grid[0])
|
||
|
def add_node(que, idx, node):
|
||
|
if len(que) <= idx:
|
||
|
que.append(node)
|
||
|
else:
|
||
|
que[idx] = node
|
||
|
def is_valid_node(node):
|
||
|
i = node[0]
|
||
|
j = node[1]
|
||
|
return i >= 0 and j >= 0 and i < row and j <column
|
||
|
flag = []
|
||
|
for i, l in enumerate(grid):
|
||
|
flag.append([])
|
||
|
for j, lee in enumerate(l):
|
||
|
flag[i].append(0)
|
||
|
for i, l in enumerate(grid):
|
||
|
for j, ele in enumerate(l):
|
||
|
val = va(grid[i][j])
|
||
|
if val == 0 : continue
|
||
|
# if (i,j) in searched_cell: continue
|
||
|
if flag[i][j] == 1: continue
|
||
|
que = [(i, j)]
|
||
|
idx = 0
|
||
|
while idx >= 0:
|
||
|
node = que[idx]
|
||
|
# if node in searched_cell: continue
|
||
|
idx -= 1
|
||
|
if flag[node[0]][node[1]] == 1: continue
|
||
|
flag[node[0]][node[1]] = 1
|
||
|
if va(grid[node[0]][node[1]]) == 0: continue
|
||
|
up = (node[0] - 1, node[1])
|
||
|
down = (node[0] + 1, node[1])
|
||
|
left = (node[0], node[1] - 1)
|
||
|
right = (node[0], node[1] + 1)
|
||
|
if is_valid_node(up):
|
||
|
idx += 1
|
||
|
add_node(que, idx, up)
|
||
|
if is_valid_node(down):
|
||
|
idx += 1
|
||
|
add_node(que,idx, down)
|
||
|
if is_valid_node(left):
|
||
|
idx += 1
|
||
|
add_node(que, idx, left)
|
||
|
if is_valid_node(right):
|
||
|
idx += 1
|
||
|
add_node(que,idx, right)
|
||
|
ans += 1
|
||
|
return ans
|
||
|
|
||
|
|