[boj] 2667 단지번호붙이기 Python
2023. 4. 8. 19:19ㆍ프로그래밍/문제풀이
728x90
n = int(input())
graph = [list(map(int, input())) for _ in range(n)]
def DFS(x, y):
graph[x][y] = 0
res = 0
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
for i in range(4):
xx = dx[i] + x
yy = dy[i] + y
if 0 <= xx < len(graph) and 0 <= yy < len(graph):
if graph[xx][yy] == 1:
res += (DFS(xx, yy) + 1)
return res
result = []
for i in range(len(graph)):
for j in range(len(graph[i])):
if graph[i][j] == 1:
result.append(DFS(i, j) + 1)
result.sort()
print(len(result))
for i in result:
print(i)
재귀를 사용한 DFS로 풀이하였다
728x90
'프로그래밍 > 문제풀이' 카테고리의 다른 글
[BOJ] 2146 다리 만들기 Python 풀이 (0) | 2023.04.13 |
---|---|
[BOJ]14395 4연산 Python 풀이 (0) | 2023.04.10 |
[BOJ] 20169 세 번 이내에 사과를 먹자 Python (0) | 2023.04.08 |
BOJ 1012 유기농 배추 Python (0) | 2023.04.06 |
[BOJ] 9237 Python | Silver V (0) | 2023.03.31 |