π¦₯ μ½ν
/BAEKJOON
[BAEKJOON python] 2667_λ¨μ§λ²νΈλΆμ΄κΈ°
μ§μ§μνμΉ΄
2022. 10. 7. 23:39
728x90
λ°μν
μ μ¬κ°ν λͺ¨μμ μ§λκ° μλ€. 1μ μ§μ΄ μλ κ³³μ, 0μ μ§μ΄ μλ κ³³μ λνλΈλ€.
μ² μλ μ΄ μ§λλ₯Ό κ°μ§κ³ μ°κ²°λ μ§μ λͺ¨μμΈ λ¨μ§λ₯Ό μ μνκ³ , λ¨μ§μ λ²νΈλ₯Ό λΆμ΄λ € νλ€.
μ¬κΈ°μ μ°κ²°λμλ€λ κ²μ μ΄λ€ μ§μ΄ μ’μ°, νΉμ μλμλ‘ λ€λ₯Έ μ§μ΄ μλ κ²½μ°λ₯Ό λ§νλ€. λκ°μ μμ μ§μ΄ μλ κ²½μ°λ μ°κ²°λ κ²μ΄ μλλ€.
μ§λλ₯Ό μ λ ₯νμ¬ λ¨μ§μλ₯Ό μΆλ ₯νκ³ , κ° λ¨μ§μ μνλ μ§μ μλ₯Ό μ€λ¦μ°¨μμΌλ‘ μ λ ¬νμ¬ μΆλ ₯νλ νλ‘κ·Έλ¨μ μμ±
첫 λ²μ§Έ μ€μλ μ§λμ ν¬κΈ° N(μ μ¬κ°νμ΄λ―λ‘ κ°λ‘μ μΈλ‘μ ν¬κΈ°λ κ°μΌλ©° 5≤N≤25)μ΄ μ λ ₯λκ³ , κ·Έ λ€μ Nμ€μλ κ°κ° Nκ°μ μλ£(0νΉμ 1)κ° μ λ ₯
첫 λ²μ§Έ μ€μλ μ΄ λ¨μ§μλ₯Ό μΆλ ₯. κ·Έλ¦¬κ³ κ° λ¨μ§λ΄ μ§μ μλ₯Ό μ€λ¦μ°¨μμΌλ‘ μ λ ¬νμ¬ ν μ€μ νλμ© μΆλ ₯
π 1. DFS
# 1) DFS
def dfs(x, y) :
global house_cnt
if x < 0 or x > n-1 or y < 0 or y > n-1 : # μ§λ λ°
return False
if graph[x][y] == False : # μ§ μμ
return False
else :
graph[x][y] = 0
house_cnt += 1 # μ§ μμΌλ©΄ λμ
for idx in range(4) : # μ¬κ·μ λ°©λ¬Έ
nx = x + dx[idx]
ny = y + dy[idx]
dfs(nx, ny)
return True
n = int(input())
graph = [list(map(int, input())) for _ in range(n)]
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
house_cnt = 0
total_cnt = 0
result = []
for i in range(n) :
for j in range(n) :
if dfs(i, j) : # κ²°κ³Όκ° True μ΄λ©΄!
result.append(house_cnt)
house_cnt = 0
total_cnt += 1
print(total_cnt)
for i in sorted(result) : # μ€λ¦μ°¨μ
print(i)
# # input
# 7
# 0110100
# 0110101
# 1110101
# 0000111
# 0100000
# 0111110
# 0111000
# # result
# 3
# 7
# 8
# 9
π 2. BFS
# 2) BFS
from collections import deque
n = int(input())
graph = []
result = []
for _ in range(n) :
graph.append(list(map(int, input())))
def bfs(x, y) :
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
queue = deque()
queue.append((x, y))
graph[x][y] = 0
count = 1
while queue :
x, y = queue.popleft()
for i in range(4) :
nx = x + dx[i]
ny = y + dy[i]
if nx >= 0 and nx < n and ny >= 0 and ny < n and graph[nx][ny] == 1 :
graph[nx][ny] = 0 # μ΄κΈ°ν
queue.append((nx, ny))
count += 1
result.append(count)
for i in range(n) :
for j in range(n) :
if graph[i][j] == 1 :
bfs(i, j)
print(len(result))
for i in sorted(result) :
print(i)
# # input
# 7
# 0110100
# 0110101
# 1110101
# 0000111
# 0100000
# 0111110
# 0111000
# # result
# 3
# 7
# 8
# 9
728x90
λ°μν