[白俊/python]10026赤色薬
18496 ワード
https://www.acmicpc.net/problem/10026
BFS
コードが少し乱れています.
基本的なbfsアルゴリズムで解く.
bfs関数でRグループの個数を計算します.全部加えました.
copylistはGをRに変換するリストです.
アルゴリズム分類
問題を解く
コードが少し乱れています.
基本的なbfsアルゴリズムで解く.
bfs関数でRグループの個数を計算します.全部加えました.
copylistはGをRに変換するリストです.
ソースコード
from collections import deque
dx=[1,-1,0,0]
dy=[0,0,1,-1]
def bfs(a,b,check):
visited=[]
visited.append((a,b))
queue=deque()
queue.append((a,b))
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
elif graph[nx][ny] == check and (nx,ny) not in visited:
graph[nx][ny]=0
visited.append((nx,ny))
queue.append((nx,ny))
return 1
def bfs2(a,b,check):
visited=[]
visited.append((a,b))
queue=deque()
queue.append((a,b))
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
elif copy[nx][ny] == check and (nx,ny) not in visited:
copy[nx][ny]=0
visited.append((nx,ny))
queue.append((nx,ny))
return 1
n=int(input())
graph=[]
for i in range(n):
graph.append(list(input()))
copy=[[] for _ in range(n)]
for i in range(n):
for j in range(n):
if graph[i][j]=='G':
copy[i].append('R')
else:
copy[i].append(graph[i][j])
result=[]
cnt=0
for i in range(n):
for j in range(n):
if graph[i][j]=='R':
graph[i][j]=0
bfs(i,j,'R')
cnt+=1
if graph[i][j]=='G':
graph[i][j]=0
bfs(i,j,'G')
cnt+=1
if graph[i][j]=='B':
graph[i][j]=0
bfs(i,j,'B')
cnt+=1
result.append(cnt)
cnt=0
for i in range(n):
for j in range(n):
if copy[i][j]=='R':
copy[i][j]=0
bfs2(i,j,'R')
cnt+=1
if copy[i][j]=='B':
copy[i][j]=0
bfs2(i,j,'B')
cnt+=1
result.append(cnt)
print(' '.join(map(str,result)))
Reference
この問題について([白俊/python]10026赤色薬), 我々は、より多くの情報をここで見つけました https://velog.io/@bye9/백준파이썬-10026-적록색약テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol