PS (Problem Solving)/Baekjoon
[백준] 1303. 전쟁-전투 - 파이썬
캐럿노트
2023. 1. 5. 00:40
문제
https://www.acmicpc.net/problem/1303
1303번: 전쟁 - 전투
첫째 줄에는 전쟁터의 가로 크기 N, 세로 크기 M(1 ≤ N, M ≤ 100)이 주어진다. 그 다음 두 번째 줄에서 M+1번째 줄에는 각각 (X, Y)에 있는 병사들의 옷색이 띄어쓰기 없이 주어진다. 모든 자리에는
www.acmicpc.net
설계
- bfs로 연결되어있는 색상 개수 count
def bfs(x, y, team):
global visit, arr
visit[x][y] = 1
q = [(x, y)]
score = 1 # bfs 들어오자마자 1칸 체크
while q:
x, y = q.pop(0)
for i in range(4):
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < M and 0 <= ny < N:
if visit[nx][ny] == 0 and arr[nx][ny] == team: # 방문한적 없고, 같은 팀인지 확인
visit[nx][ny] = 1
score += 1 # 한칸 체크할때마다 점수 + 1
q.append((nx, ny))
return score
N, M = map(int, input().split())
arr = [list(input()) for _ in range(M)]
visit = [[0] * N for _ in range(M)]
score_B, score_W = 0, 0
for x in range(M): # 행
for y in range(N): # 열
if arr[x][y] == 'B' and visit[x][y] == 0:
score = bfs(x, y, 'B')
score_B += score ** 2
elif arr[x][y] == 'W' and visit[x][y] == 0:
score = bfs(x, y, 'W')
score_W += score ** 2
print(score_W, score_B)