λ¬Έμ
λ°±μ€ μ¨λΌμΈ μ μ§ - 10026λ²
νμ΄ κ³Όμ
μ
λ ₯λ board
μ ν¬κΈ°κ° ν¬μ§ μμΌλ―λ‘ DFS
νμμ ν΅ν΄ λͺ¨λ ꡬκ°μ μ°Ύμ쀬μ΅λλ€.
μλ§Ήμ΄ μλ μ¬λκ³Ό μλ μ¬λμ νμ μ μ½μ‘°κ±΄μ΄ λ€λ₯΄κΈ° λλ¬Έμ κ°κ° visit
λ°°μ΄μ λ§λ€μ΄μ λ°λ‘ νμμ μννμ΅λλ€.
2λ²μ DFS
λ₯Ό μνν΄λ μ΄ μκ° λ³΅μ‘λκ° O(2n)
μ΄κΈ° λλ¬Έμ μκ° λ΄μ μνμ΄ κ°λ₯νμ΅λλ€.
μ½λ
import sys
sys.setrecursionlimit(10**6)
N = int(input())
board = []
for _ in range(N):
board.append(list(sys.stdin.readline()[:-1]))
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def dfs(x, y, visit, decision):
visit[x][y] = 1
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < N and 0 <= ny < N:
if not visit[nx][ny] and board[nx][ny] in decision:
dfs(nx, ny, visit, decision)
def solution():
normal_visit = [[0]*N for _ in range(N)]
sick_visit = [[0]*N for _ in range(N)]
ans = [0, 0]
for r in range(N):
for c in range(N):
if not normal_visit[r][c]:
dfs(r, c, normal_visit, [board[r][c]])
ans[0] += 1
if not sick_visit[r][c]:
if board[r][c] == 'R' or board[r][c] == 'G':
dfs(r, c, sick_visit, ['R', 'G'])
else:
dfs(r, c, sick_visit, ['B'])
ans[1] += 1
return ' '.join(map(str, ans))
print(solution())
λ°μν
'π algorithm > boj' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
BOJ 1389 - μΌλΉ λ² μ΄μ»¨μ 6λ¨κ³ λ²μΉ (0) | 2021.06.09 |
---|---|
BOJ 2644 - μ΄μκ³μ° (0) | 2021.06.09 |
BOJ 3135 - λΌλμ€ (0) | 2021.06.09 |
BOJ 13410 - κ±°κΎΈλ‘ κ΅¬κ΅¬λ¨ (0) | 2021.06.08 |
BOJ 2252 - μ€ μΈμ°κΈ° (0) | 2021.06.07 |
π¬ λκΈ