프로그래밍/알고리즘

BOJ 1303 · 전쟁 - 전투

반응형


알고리즘 분류 : DFS, BFS  


각 팀의 전투력 합을 구하는 문제다. 플러드 필을 하면 된다.


  • 시작 알파벳을 기준으로 DFS나 BFS를 통해 인접하면서 같은 알파벳을 찾는다.
  • 모인 팀의 인원을 제곱한 후, 각 팀 전투력에 더한다.
  • W팀, B팀의 전투력을 각각 출력한다.





C++ 소스코드


#include <cstdio>

int n, m, w, b;
char a[101][101];
bool check[100][100];
const int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};

int dfs(int x, int y, char c) {
    int ret = 1;
    check[x][y] = true;
    for (int i=0; i<4; i++) {
        int nx = x+dx[i], ny = y+dy[i];
        if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
        if (!check[nx][ny] && a[nx][ny] == c) ret += dfs(nx, ny, c);
    }
    return ret;
}

int main() {
    scanf("%d %d", &m, &n);
    for (int i=0; i<n; i++) scanf("%s", a[i]);
    for (int i=0; i<n; i++) {
        for (int j=0; j<m; j++) {
            if (!check[i][j]) {
                int k = dfs(i, j, a[i][j]);
                if (a[i][j] == 'W') w += k*k;
                else b += k*k;
            }
        }
    }
    printf("%d %d\n", w, b);
    return 0;
}




Python 3 소스코드


from collections import deque
m, n = map(int, input().split())
a = [list(input().strip()) for _ in range(n)]
check = [[False]*m for _ in range(n)]
w, b = 0, 0

def bfs(i, j, c):
    q = deque()
    q.append((i, j))
    cnt = 1
    check[i][j] = True
    while q:
        x, y = q.popleft()
        for dx, dy in (-1,0), (1,0), (0,-1), (0,1):
            nx, ny = x+dx, y+dy
            if nx < 0 or nx >= n or ny < 0 or ny >= m:
                continue
            if not check[nx][ny] and a[nx][ny] == c:
                q.append((nx, ny))
                check[nx][ny] = True
                cnt += 1
    return cnt

for i in range(n):
    for j in range(m):
        if not check[i][j]:
            k = bfs(i, j, a[i][j])
            if a[i][j] == 'W':
                w += k*k
            else:
                b += k*k
print(w, b)


✓ 파이썬은 BFS로 구현했다.




참고



반응형