[3085] 사탕 게임

HeeSeong·2024년 10월 26일
0

백준

목록 보기
116/116
post-thumbnail

🔗 문제 링크

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


🔍 문제 설명


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

가장 처음에 N×N크기에 사탕을 채워 놓는다. 사탕의 색은 모두 같지 않을 수도 있다. 상근이는 사탕의 색이 다른 인접한 두 칸을 고른다. 그 다음 고른 칸에 들어있는 사탕을 서로 교환한다. 이제, 모두 같은 색으로 이루어져 있는 가장 긴 연속 부분(행 또는 열)을 고른 다음 그 사탕을 모두 먹는다.

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


⚠️ 제한사항


  • 3 ≤ N ≤ 50

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



🗝 풀이 (언어 : Java)


특정 지점 기준 매번 오른쪽과 아래쪽 지점의 값과 교환하는 방식으로 찾는다.
이것을 모든 지점에 대해 탐색한다.

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

public class Main {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int N = Integer.parseInt(br.readLine());
		String[][] matrix = new String[N][N];
		for (int i = 0; i < N; i++) {
			matrix[i] = br.readLine().split("");
		}
		br.close();
		solution(matrix);
	}

	private static void solution(String[][] matrix) {
		int size = matrix.length;
		int answer = 1;
		for (int i = 0; i < size; i++) {
			for (int j = 0; j < size; j++) {
				String color = matrix[i][j];
				//오른쪽
				if (j + 1 < size) {
					String rightColor = matrix[i][j + 1];
					if (!color.equals(rightColor)) {
						matrix[i][j + 1] = color;
						matrix[i][j] = rightColor;
						answer = Math.max(answer, countRowColCandies(matrix, size));
						matrix[i][j + 1] = rightColor;
						matrix[i][j] = color;
					}
				}
				//아래쪽
				if (i + 1 < size) {
					String downColor = matrix[i + 1][j];
					if (!color.equals(downColor)) {
						matrix[i + 1][j] = color;
						matrix[i][j] = downColor;
						answer = Math.max(answer, countRowColCandies(matrix, size));
						matrix[i + 1][j] = downColor;
						matrix[i][j] = color;
					}
				}
			}
		}
		System.out.println(answer);
	}

	private static int countRowColCandies(String[][] matrix, int size) {
		int max = 0;
		for (int i = 0; i < size; i++) {
			int rowCount = 1;
			int colCount = 1;
			for (int j = 1; j < size; j++) {
				if (matrix[i][j].equals(matrix[i][j - 1])) {
					rowCount++;
					max = Math.max(max, rowCount);
					continue;
				}
				rowCount = 1;
			}
			for (int j = 1; j < size; j++) {
				if (matrix[j][i].equals(matrix[j - 1][i])) {
					colCount++;
					max = Math.max(max, colCount);
					continue;
				}
				colCount = 1;
			}
		}
		return max;
	}

}
profile
끊임없이 성장하고 싶은 개발자

0개의 댓글