Algorithm

BF / 백준 3085 사탕 게임

Dear-J 2025. 5. 26. 12:06

 

문제 접근

2차원 배열 하나씩 비교

>> 만약 문자가 다르면 둘이 바꿈

 

바꾸고 나면

>> 같은 색이 가장 긴 연속부분 각각의 열, 행 기준으로 계산

>> 끝나면 다시 2차원 배열 전으로 돌림

풀이

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class S3085 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

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

        char[][] candy = new char[N][N];

        for (int i = 0; i < N; i++) {
            String s = br.readLine();
            for (int j = 0; j < N; j++) {
                candy[i][j] = s.charAt(j);
            }
        }

        int result = com(candy, N);
        System.out.println(result);
    }

    public static int com(char[][] arr, int N) {
        int max = 1;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N - 1; j++) {
                if (arr[i][j] != arr[i][j + 1]) {
                    char s = arr[i][j];
                    char ss = arr[i][j + 1];
                    arr[i][j] = ss;
                    arr[i][j + 1] = s;
                    max = Math.max(max, same(arr, N));

                    arr[i][j] = s;
                    arr[i][j + 1] = ss;
                }
            }
        }

        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N - 1; j++) {
                if (arr[j][i] != arr[j + 1][i]) {
                    char s = arr[j][i];
                    char ss = arr[j + 1][i];
                    arr[j][i] = ss;
                    arr[j + 1][i] = s;
                    max = Math.max(max, same(arr, N));

                    arr[j][i] = s;
                    arr[j + 1][i] = ss;
                }
            }
        }
        return max;
    }

    public static int same(char[][] arr, int N) {
        int cnt = 1;
        int max = 1;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N - 1; j++) {
                if (arr[i][j] == arr[i][j + 1]) {
                    cnt += 1;
                } else {
                    max = Math.max(max, cnt);
                    cnt = 1;
                }
            }
            max = Math.max(max, cnt);
            cnt = 1;
        }

        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N - 1; j++) {
                if (arr[j][i] == arr[j + 1][i]) {
                    cnt += 1;
                } else {
                    max = Math.max(max, cnt);
                    cnt = 1;
                }
            }
            max = Math.max(max, cnt);
            cnt = 1;
        }
        return max;
    }
}

 

'Algorithm' 카테고리의 다른 글

BF / 백준 1107 리모컨  (0) 2025.05.28
BF / 백준 1476 날짜 계산  (0) 2025.05.27
BF / 백준 2309 일곱 난쟁이  (0) 2025.05.25
DP / 백준 2133 타일 채우기  (0) 2025.05.25
DP / 백준 13398 연속합 2  (0) 2025.05.25