๋ฌธ์
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])
'๐๏ธ Algorithm > ๐ฉ ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๐ฉ [๋ฐฑ์ค] [Python] [๊ตฌํ] 17478๋ฒ_์ฌ๊ทํจ์๊ฐ ๋ญ๊ฐ์? (0) | 2022.11.06 |
---|---|
๐ฉ [๋ฐฑ์ค] [Python] [๊ตฌํ] 1475๋ฒ_๋ฐฉ ๋ฒํธ (0) | 2022.11.05 |
๐ฉ [๋ฐฑ์ค] [Python] [Class3] 1927๋ฒ_์ต์ ํ (0) | 2022.11.04 |
๐ฉ [๋ฐฑ์ค] [Python] [๊ตฌํ] 1780๋ฒ_์ข ์ด์ ๊ฐ์ (0) | 2022.11.04 |
๐ฉ [๋ฐฑ์ค] [Python] [๊ตฌํ] 10815๋ฒ_์ซ์ ์นด๋ (0) | 2022.11.03 |