본문 바로가기
Algorithm/baekjoon

[파이썬]baekjoon 1303: 전쟁 - 전투

by 갈잃자 2023. 1. 7.

https://www.acmicpc.net/problem/1303

 

1303번: 전쟁 - 전투

첫째 줄에는 전쟁터의 가로 크기 N, 세로 크기 M(1 ≤ N, M ≤ 100)이 주어진다. 그 다음 두 번째 줄에서 M+1번째 줄에는 각각 (X, Y)에 있는 병사들의 옷색이 띄어쓰기 없이 주어진다. 모든 자리에는

www.acmicpc.net


bfs문제

 

W나 B로 시작하는지 확인한 뒤, W집군과 B집군의 값을 찾은 후 출력하면 된다.

 

n,m = list(map(int,input().split()))

arr = [list(input()) for _ in range(m)]
visit = [[0]*n for _ in range(m)]
w = 0
b = 0
def bfs(start):
    global visit, w, b
    q = []
    q.append(start)
    Wyes = True
    if start[2] == 'W':
        Wyes = True
    else:
        Wyes = False

    cnt = 1
    directy = [-1,1,0,0]
    directx = [0,0,-1,1]

    while q:
        nowy, nowx, now = q.pop(0)
        for i in range(4):
            dy = nowy + directy[i]
            dx = nowx + directx[i]

            if 0<=dy<m and 0<=dx<n:
                if visit[dy][dx] == 1: continue
                if now != arr[dy][dx]: continue
                visit[dy][dx] = 1
                cnt +=1
                q.append((dy,dx,arr[dy][dx]))
    if Wyes == True:
        w += cnt**2
        return
    else:
        b += cnt**2
        return


for y in range(m):
    for x in range(n):
        if arr[y][x] =="W" and visit[y][x] == 0:
            visit[y][x] = 1
            bfs([y,x,"W"])
        if arr[y][x] =="B" and visit[y][x] ==0:
            visit[y][x] = 1
            bfs([y,x,"B"])
print(w, b)

댓글