-
[백준] 10026. 적록색약 (BFS)코테 준비/DFS, BFS 2023. 2. 4. 03:02
연속된 영역의 개수를 세는 문제이다
from collections import deque dx=[-1,1,0,0] dy=[0,0,-1,1] def bfs(graph,x,y): queue=deque() queue.append((x,y)) color=graph[x][y] graph[x][y]=0 while queue: x,y=queue.popleft() for i in range(4): nx=x+dx[i] ny=y+dy[i] if nx<0 or ny<0 or nx>=n or ny>=n: continue if graph[nx][ny]==color: #현재 칸의 색깔과 상하좌우의 색이 같으면 graph[nx][ny]=0 #0으로 방문처리 queue.append((nx,ny)) n=int(input()) graph=[[0]*n for _ in range(n)] #일반 그래프 rd_graph=[[0]*n for _ in range(n)] #적록색약 그래프 for i in range(n): k=input() graph[i]=list(map(str,k)) rd_graph[i]=list(k.replace('G','R')) # 빨간색과 초록색을 구분 못하므로 초록색을 빨간색으로 바꿈 count=0 #일반 그래프 영역개수 count2=0 #적록색약 그래프 영역개수 for i in range(n): for j in range(n): if graph[i][j]!=0: #방문하지 않았으면 bfs(graph,i,j) count+=1 for i in range(n): for j in range(n): if rd_graph[i][j]!=0: bfs(rd_graph,i,j) count2+=1 print(count,count2)
'코테 준비 > DFS, BFS' 카테고리의 다른 글
[백준] 16236. 아기상어 (BFS) -너무 어려움..꼭 다시풀기!! (0) 2023.02.09 [백준] 1389. 케빈 베이컨의 6단계 법칙 (0) 2023.02.07 [백준] 11403. 경로찾기 (bfs) (1) 2023.02.02 [백준] 1697. 숨바꼭질 (다시 풀어보기) (0) 2023.02.02 [백준] 7576. 토마토 (DFS) (0) 2023.01.31