Programing/BaekJoon

[JAVA] 백준 3085 : 사탕게임

블스뜸 2025. 3. 29. 19:03

부르스포스 완전탐색 학습용 문제풀이

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int x = Integer.parseInt(br.readLine());

        char[][] candi = new char[x][x];
        for (int i = 0; i < x; i++) {
            candi[i] = br.readLine().toCharArray();
        }

        int max = 0;
        for (int i = 0; i < x; i++) {
            for (int j = 0; j < x; j++) {
                max = Math.max(max, check(candi, x));
                if (j + 1 < x) {
                    swap(candi, i, j, i, j + 1);
                    max = Math.max(max, check(candi, x));
                    swap(candi, i, j, i, j + 1);
                }
                if (i + 1 < x) {
                    swap(candi, i, j, i + 1, j);
                    max = Math.max(max, check(candi, x));
                    swap(candi, i, j, i + 1, j);
                }
            }
        }

        bw.write(String.valueOf(max));
        bw.flush();
        bw.close();
        br.close();
    }

    public static void swap(char[][] arr, int x1, int y1, int x2, int y2) {
        char temp = arr[x1][y1];
        arr[x1][y1] = arr[x2][y2];
        arr[x2][y2] = temp;
    }

    public static int check(char[][] arr, int size) {
        int max = 0;
        for (int i = 0; i < size; i++) {
            int count = 1;
            for (int j = 0; j < size - 1; j++) {
                if (arr[i][j] == arr[i][j + 1]) {
                    count++;
                } else {
                    count = 1;
                }
                max = Math.max(max, count);
            }
            count = 1;
            for (int j = 0; j < size - 1; j++) {
                if (arr[j][i] == arr[j + 1][i]) {
                    count++;
                } else {
                    count = 1;
                }
                max = Math.max(max, count);
            }
        }
        return max;
    }
}