[Algorithm - Baekjoon] 1303번 전쟁 - 전투

nunu·2023년 12월 17일
0

Algorithm

목록 보기
102/142

문제

전쟁은 어느덧 전면전이 시작되었다. 결국 전투는 난전이 되었고, 우리 병사와 적국 병사가 섞여 싸우게 되었다. 그러나 당신의 병사들은 흰색 옷을 입고, 적국의 병사들은 파란색 옷을 입었기 때문에 서로가 적인지 아군인지는 구분할 수 있다. 문제는 같은 팀의 병사들은 모이면 모일수록 강해진다는 사실이다.

N명이 뭉쳐있을 때는 N2의 위력을 낼 수 있다. 과연 지금 난전의 상황에서는 누가 승리할 것인가? 단, 같은 팀의 병사들이 대각선으로만 인접한 경우는 뭉쳐 있다고 보지 않는다.

입력

첫째 줄에는 전쟁터의 가로 크기 N, 세로 크기 M(1 ≤ N, M ≤ 100)이 주어진다. 그 다음 두 번째 줄에서 M+1번째 줄에는 각각 (X, Y)에 있는 병사들의 옷색이 띄어쓰기 없이 주어진다. 모든 자리에는 병사가 한 명 있다. B는 파란색, W는 흰색이다. 당신의 병사와 적국의 병사는 한 명 이상 존재한다.

출력

첫 번째 줄에 당신의 병사의 위력의 합과 적국의 병사의 위력의 합을 출력한다.

예제1 - 입력

5 5
WBWWW
WWWWW
BBBBB
BBBWW
WWWWW

예제1 - 출력

130 65

제출코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main {
    static char[][] map;
    static int n, m;
    static boolean[][] visited;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        StringTokenizer st = new StringTokenizer(br.readLine());
        n = Integer.parseInt(st.nextToken());
        m = Integer.parseInt(st.nextToken());

        map = new char[m][n];
        for (int i = 0; i < m; i++) {
            map[i] = br.readLine().toCharArray();
        }
        visited = new boolean[m][n];
        int wTeam = 0, bTeam = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (!visited[i][j]) {
                    int temp = bfs(map[i][j], new Pair(i, j));
                    if (map[i][j] == 'W') {
                        wTeam += temp;
                    }
                    else {
                        bTeam += temp;
                    }
                }

            }
        }
        System.out.println(wTeam + " " + bTeam);
    }
    static int bfs(char c, Pair str) {
        int sum = 1;
        int[] dx = {-1, 1, 0, 0};
        int[] dy = {0, 0, -1, 1};

        Queue<Pair> queue = new LinkedList<>();
        queue.offer(str);
        visited[str.x][str.y] = true;
        while (!queue.isEmpty()) {
            Pair now = queue.poll();
            for (int i = 0; i < dx.length; i++) {
                int tx = now.x + dx[i];
                int ty = now.y + dy[i];
                if (tx < 0 || tx >= m || ty < 0 || ty >= n)
                    continue;

                if (!visited[tx][ty] && map[tx][ty] == c) {
                    visited[tx][ty] = true;
                    queue.offer(new Pair(tx, ty));
                    sum++;
                }
            }
        }
        return sum * sum;
    }
    static class Pair {
        public int x;
        public int y;
        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
}
profile
Hello, I'm nunu

0개의 댓글