๐๏ธ Algorithm/๐ฉ ๋ฐฑ์ค
๐ฉ [๋ฐฑ์ค] [Python] [DFS/BFS] 2667๋ฒ_๋จ์ง๋ฒํธ๋ถ์ด๊ธฐ
Dbswnstjd
2022. 11. 4. 21:07
๋ฌธ์
https://www.acmicpc.net/problem/2667
2667๋ฒ: ๋จ์ง๋ฒํธ๋ถ์ด๊ธฐ
<๊ทธ๋ฆผ 1>๊ณผ ๊ฐ์ด ์ ์ฌ๊ฐํ ๋ชจ์์ ์ง๋๊ฐ ์๋ค. 1์ ์ง์ด ์๋ ๊ณณ์, 0์ ์ง์ด ์๋ ๊ณณ์ ๋ํ๋ธ๋ค. ์ฒ ์๋ ์ด ์ง๋๋ฅผ ๊ฐ์ง๊ณ ์ฐ๊ฒฐ๋ ์ง์ ๋ชจ์์ธ ๋จ์ง๋ฅผ ์ ์ํ๊ณ , ๋จ์ง์ ๋ฒํธ๋ฅผ ๋ถ์ด๋ ค ํ๋ค. ์ฌ
www.acmicpc.net
ํ์ด
DFS๋ฅผ ์ฌ์ฉํ ํ์ด
# ๋ฐฑ์ค 2667๋ฒ ๋ฌธ์ - ๋จ์ง๋ฒํธ๋ถ์ด๊ธฐ
n = int(input())
graph = []
num = []
for i in range(n):
graph.append(list(map(int, input())))
dx = [0,0,1,-1]
dy = [1,-1,0,0]
def DFS(x,y):
if x < 0 or x >= n or y < 0 or y >= n:
return False
if graph[x][y] == 1:
global cnt
cnt += 1
graph[x][y] = 0
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
DFS(nx, ny)
return True
return False
cnt = 0
result = 0
for i in range(n):
for j in range(n):
if DFS(i, j) == True:
num.append(cnt)
result += 1
cnt = 0
num.sort()
print(result)
for i in num:
print(i)
BFS๋ฅผ ์ฌ์ฉํ ํ์ด
# BFS
from collections import deque
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def bfs(graph, a, b):
n = len(graph)
queue = deque()
queue.append((a, b))
graph[a][b] = 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 or nx >= n or ny < 0 or ny >= n:
continue
if graph[nx][ny] == 1:
graph[nx][ny] = 0
queue.append((nx, ny))
count += 1
return count
n = int(input())
graph = []
for i in range(n):
graph.append(list(map(int, input())))
cnt = []
for i in range(n):
for j in range(n):
if graph[i][j] == 1:
cnt.append(bfs(graph, i, j))
cnt.sort()
print(len(cnt))
for i in range(len(cnt)):
print(cnt[i])