Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

JAVA Developer Training

48. 1303번 전쟁-전투 본문

백준 알고리즘

48. 1303번 전쟁-전투

Romenest 2022. 1. 5. 20:04

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

 

1303번: 전쟁 - 전투

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

www.acmicpc.net

import java.io.*;
import java.util.*;

//1303
public class training11 {
    public static String[][] map;
    public static boolean[][] visited;
    public static int N, M, cnt;
    public static int[] result = { 0, 0 };
    public static int[] dx = { 0, 1, 0, -1 };
    public static int[] dy = { 1, 0, -1, 0 };

    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 String[N][M];
        visited = new boolean[N][M];
        for (int i = 0; i < N; i++) {
            String string = br.readLine();
            for (int j = 0; j < string.length(); j++) {
                String[] split = string.split("");
                map[i][j] = split[j];
            }
        }

        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                if (!visited[i][j]) {
                    cnt = 0;
                    dfs(i, j);
                    if (map[i][j].equals("W")) {
                        result[0] = result[0] + (cnt * cnt);
                    }
                    if (map[i][j].equals("B")) {
                        result[1] += cnt * cnt;
                    }
                }
            }
        }
        System.out.println(result[0] + " " + result[1]);

        // for(int k=0; k<M; k++){
        // System.out.println(Arrays.toString(map[k]));
        // }
    }

    public static void dfs(int width, int height) {
        visited[width][height] = true;
        cnt++;
        for (int i = 0; i < 4; i++) {
            int nx = width + dx[i];
            int ny = height + dy[i];

            if (nx < 0 || ny < 0 || nx >= N || ny >= M) {
                continue;
            }

            if (!visited[nx][ny] && map[nx][ny].equals(map[width][height])) {
                visited[nx][ny] = true;
                dfs(nx, ny);
            }
        }
    }
}

'백준 알고리즘' 카테고리의 다른 글

50. 1743번 음식물 피하기  (0) 2022.01.05
49. 2178번 미로탐색  (0) 2022.01.05
47. 8911번 거북이  (0) 2021.12.31
46. 1141번 접두사  (0) 2021.12.31
45. 2293번 동전 1  (0) 2021.12.20