BOJ 3085

2020-04-30

위 문제는 백준 사이트의 알고리즘 3085 문제에 관한 설명입니다.


문제

상근이는 어렸을 적에 “봄보니 (Bomboni)” 게임을 즐겨했다.

가장 처음에 N×N크기에 사탕을 채워 놓는다.

사탕의 색은 모두 같지 않을 수도 있다. 상근이는 사탕의 색이 다른 인접한 두 칸을 고른다.

그 다음 고른 칸에 들어있는 사탕을 서로 교환한다.

이제, 모두 같은 색으로 이루어져 있는 가장 긴 연속 부분(행 또는 열)을 고른 다음 그 사탕을 모두 먹는다.

사탕이 채워진 상태가 주어졌을 때, 상근이가 먹을 수 있는 사탕의 최대 개수를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 보드의 크기 N이 주어진다. (3 ≤ N ≤ 50)

다음 N개 줄에는 보드에 채워져 있는 사탕의 색상이 주어진다. 빨간색은 C, 파란색은 P, 초록색은 Z, 노란색은 Y로 주어진다.

사탕의 색이 다른 인접한 두 칸이 존재하는 입력만 주어진다.

출력

첫째 줄에 상근이가 먹을 수 있는 사탕의 최대 개수를 출력한다.

import java.util.Scanner;

public class Candy{
	
	static int n;
	static char candy[][];
	static int answer;
	
	public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        
        n = sc.nextInt();
        candy = new char[n][n];
        
        for(int i=0;i<n;i++){
            candy[i] = sc.next().toCharArray();
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n - 1; j++) {
                char temp = candy[i][j];
                candy[i][j] = candy[i][j + 1];
                candy[i][j + 1] = temp;
                check();
                temp = candy[i][j + 1];
                candy[i][j + 1] = candy[i][j];
                candy[i][j] = temp;

                temp = candy[j][i];
                candy[j][i] = candy[j + 1][i];
                candy[j + 1][i] = temp;
                check();
                temp = candy[j + 1][i];
                candy[j + 1][i] = candy[j][i];
                candy[j][i] = temp;
            }
        }
        System.out.println(answer);
    }

    public static void check() {
        for (int i = 0; i < n; i++) {
            int count = 1;
            for (int j = 1; j < n; j++) {
                if (candy[i][j] == candy[i][j - 1]) {
                    ++count;
                } else {
                    answer = max(answer, count);
                    count = 1;
                }
            }
            answer = max(answer, count);
        }

        for (int i = 0; i < n; i++) {
            int count = 1;
            for (int j = 1; j < n; j++) {
                if (candy[j][i] == candy[j - 1][i]) {
                    ++count;
                } else {
                    answer = max(answer, count);
                    count = 1;
                }
            }
            answer = max(answer, count);
        }
    }

    public static int max(int x, int y) {
        if(x > y) return x;
        else return y;
    }
}

인접한 사탕을 위치를 바꾸면서 최대값이면 먹는 것을 구현하는 것이 문제입니다.

인접한 사탕은 위, 아래, 옆이고 대각선은 포함하지 않습니다.

일단 사탕 자리를 바꿔서 최대 개수를 구한 후,

사탕 자리를 원래대로 되돌려 놓는 것이 중요합니다.

사탕게임