- Problem
1020. Number of Enclaves
- 내 풀이 (BFS)
SEA = 0
LAND = 1
VISITED = -1
class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
def bfs(y, x):
q = deque([(y, x)])
grid[y][x] = VISITED
can_move = True
moves = 1
while q:
y, x = q.popleft()
if y in [0, M - 1] or x in [0, N - 1]:
can_move = False
for dy, dx in ((-1, 0), (1, 0), (0, -1), (0, 1)):
ny = y + dy
nx = x + dx
if 0 <= ny < M and 0 <= nx < N and grid[ny][nx] == LAND:
q.append((ny, nx))
grid[ny][nx] = VISITED
moves += 1
return moves if can_move else 0
M, N = len(grid), len(grid[0])
return sum(bfs(i, j) for i in range(M) for j in range(N) if grid[i][j] == LAND)
- 결과