νλ²ν κ·Έλν νμ λ¬Έμ .
μμ΄λμ΄
bfs λλ dfsλ₯Ό νμ©νμ¬ λ¬Έμ λ₯Ό ν΄κ²°νλ©΄ λλ€.
1. κ·Έλν μμμ§μ 'I'λ μΊ νΌμ€ μ 보λ₯Ό λ°μμ¬ λ 미리 μ°Ύμλ μ μλ€.
2. λΉκ³΅κ° λΏμλλΌ μ¬λμ΄ μλ μ§μ 'P'λ μ΄λ κ°λ₯νλ€.
3. μ λ΅μ μΆλ ₯ν λ, λ΅μ΄ 0λͺ μ΄λ©΄ 0μ΄ μλ "TT"λ₯Ό μΆλ ₯ν΄ μ£Όμ.
μ 체 μ½λ
from collections import deque
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
campus = [] # μΊ νΌμ€ μ 보λ₯Ό λ΄λ 리μ€νΈ
ix, iy = 0, 0 # μ΅μ΄ μμ μμΉμ μ’ν ix, iy
answer = 0 # λ§λ μ μλ μ¬λμ μ, μΆλ ₯κ°
N, M = map(int, input().split()) # μΊ νΌμ€ ν¬κΈ° μ
λ ₯
for i in range(N):
campus.append(list(input()))
for j in range(M):
if campus[i][j] == 'I': # μμ μμΉ μ°ΎκΈ°
ix, iy = i, j
visited = [[0] * M for _ in range(N)] # λ°©λ¬Έ μ 보λ₯Ό λ΄λ 리μ€νΈ
deq = deque()
deq.append([ix, iy]) # μ΅μ΄ μμ μμΉ insert
while deq: # νκ° λΉ λκΉμ§
x, y = deq.popleft()
for i in range(4): # μνμ’μ° νμ
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < N and 0 <= ny < M and visited[nx][ny] == 0: # λ°©λ¬Έ μνμΌλ©΄
visited[nx][ny] = 1 # λ°©λ¬Έ νμ
if campus[nx][ny] == 'O': # λΉ κ³΅κ° μ΄λ©΄
deq.append([nx, ny])
elif campus[nx][ny] == 'P': # μ¬λ μ΄λ©΄
deq.append([nx, ny])
answer += 1 # λ§λ μ¬λ μ μ¦κ°
print('TT' if answer == 0 else answer) # μ λ΅ μΆλ ₯
μ½λ μ€λͺ
for i in range(N):
campus.append(list(input()))
for j in range(M):
if campus[i][j] == 'I': # μμ μμΉ μ°ΎκΈ°
ix, iy = i, j
μΊ νΌμ€ μ 보λ₯Ό μ λ ₯λ°μΌλ©΄μ μμ μμΉλ₯Ό 미리 μ°Ύμλ€.
deq = deque()
deq.append([ix, iy]) # μ΅μ΄ μμ μμΉ insert
while deq: # νκ° λΉ λκΉμ§
x, y = deq.popleft()
for i in range(4): # μνμ’μ° νμ
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < N and 0 <= ny < M and visited[nx][ny] == 0: # λ°©λ¬Έ μνμΌλ©΄
visited[nx][ny] = 1 # λ°©λ¬Έ νμ
if campus[nx][ny] == 'O': # λΉ κ³΅κ° μ΄λ©΄
deq.append([nx, ny])
elif campus[nx][ny] == 'P': # μ¬λ μ΄λ©΄
deq.append([nx, ny])
answer += 1 # λ§λ μ¬λ μ μ¦κ°
μ΅μ΄ μμ μμΉλ₯Ό κΈ°μ€μΌλ‘ bfsνμμ νλ€. μΊ νΌμ€ ν¬κΈ°μ λ¬Έμ 쑰건μ λ§κ² ifλ¬Έμ μμ±ν΄ μ€λ€.
'𧩠Problem Solving > [λ°±μ€]' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[λ°±μ€] 14940 μ¬μ΄ μ΅λ¨κ±°λ¦¬ (python νμ΄μ¬) (0) | 2024.03.20 |
---|---|
[λ°±μ€] 1205 λ±μ ꡬνκΈ° (python νμ΄μ¬) (0) | 2024.03.19 |
[λ°±μ€] 18110 solved.ac (+λ°μ¬λ¦Ό ν¨μ roundμ λν΄) (python νμ΄μ¬) (0) | 2023.08.23 |
[λ°±μ€] 2839 μ€ν λ°°λ¬ (feat.DP) (python νμ΄μ¬) (0) | 2023.08.20 |
[λ°±μ€] 2447 λ³ μ°κΈ° - 10 (python νμ΄μ¬) (0) | 2023.07.30 |