class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
ans = 0
m = len(grid)
n = len(grid[0])
for i in range(m) :
for j in range(n) :
if grid[i][j] == "1" :
ans += 1
self.check(grid, i, j)
return ans
def check(self, grid, i, j) :
dir = [
[1, 0],
[0, 1],
[-1, 0],
[0, -1]
]
stack = [[i,j]]
while stack :
i, j = stack.pop()
grid[i][j] = 0
for direction in dir :
X, Y = direction
nextX, nextY = X + j, Y + i
if nextX >= 0 and nextX < len(grid[0]) and nextY >= 0 and nextY < len(grid) and grid[nextY][nextX] == '1' :
stack.append([nextY, nextX])
대표적인 bfs, dfs 기본문제인 것 같다.
'컴퓨터 > 코테' 카테고리의 다른 글
릿코드 338 - 2진법 변환 (0) | 2021.08.10 |
---|---|
릿코드 876 - Middle of the Linked List (0) | 2021.08.09 |
릿코드62 - Unique paths [dp] (0) | 2021.08.07 |
릿코드155 - min Stack [스택] (0) | 2021.08.07 |
릿코드 2 - 두 수 더하기 (리스트) (0) | 2021.08.05 |