문제 : https://www.acmicpc.net/problem/2667
▶ 코드( 재귀 ver. )
n = int(input())
m = []
for _ in range(n):
num = str(input())
num = list(map(int, num))
m.append(num)
#print(m)
visited = [[0]*n for i in range(n)]
dx = [1,-1,0,0]
dy = [0,0,1,-1]
def isInGraph(r, l):
if r < 0 or r >= n or l < 0 or l >= n:
return False
return True
def bfs(r, l):
visited[r][l] = 1
cnt = 1
tx = 0
ty = 0
for i in range(4):
tx = r + dx[i]
ty = l + dy[i]
if isInGraph(tx, ty):
if visited[tx][ty] == 0 and m[tx][ty] == m[r][l]:
cnt += bfs(tx, ty)
return cnt
ans = []
for i in range(n):
for j in range(n):
if visited[i][j] == 0 and m[i][j] != 0:
ans.append(bfs(i, j))
ans.sort()
print(len(ans))
for a in ans:
print(a)
'■코테 중요개념 > BFS' 카테고리의 다른 글
[백준 7576] 토마토 (0) | 2020.05.30 |
---|---|
[백준 2178] 미로 탐색 (0) | 2020.05.29 |
[백준 1012] 유기농 배추 (0) | 2020.05.28 |
[백준 2606] 바이러스 (0) | 2020.05.28 |
[백준 1260] DFS와 BFS (0) | 2020.05.28 |