본문 바로가기

ALGORITHM

백준 3085 사탕 게임 (Java)

1. 문제 링크

 

3085번: 사탕 게임

예제 3의 경우 4번 행의 Y와 C를 바꾸면 사탕 네 개를 먹을 수 있다.

www.acmicpc.net

 

2. 문제 및 입출력예제

 

3. 문제 풀이

인접한 사탕이 다른 색일 경우 바꾸면서 최댓값을 찾는다.

사방탐색을 하려고 했는데 교환이라서 오른쪽과 아래쪽만 확인해도 전부 볼 수 있다.

교환 전 후로 값을 바꿔주는 과정을 넣어서 원래 배열을 유지하게 했다.

 

4. 코드

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

public class Main {
	private static int N;
	private static int max = 0;

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		N = Integer.parseInt(br.readLine());
		String[][] map = new String[N][N];

		for (int i = 0; i < N; i++) {
			map[i] = br.readLine().split("");
		}

		String temp;
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < N; j++) {
				if (j + 1 < N) { // 우
					temp = map[i][j];
					map[i][j] = map[i][j + 1];
					map[i][j + 1] = temp;

					solve(map);

					temp = map[i][j];
					map[i][j] = map[i][j + 1];
					map[i][j + 1] = temp;

				}

				if (i + 1 < N) { // 하
					temp = map[i][j];
					map[i][j] = map[i + 1][j];
					map[i + 1][j] = temp;
					
					solve(map);

					temp = map[i][j];
					map[i][j] = map[i + 1][j];
					map[i + 1][j] = temp;

				}
			}
		}

		System.out.println(max);
	}

	private static void solve(String[][] map) {
		for (int x = 0; x < N; x++) {
			int count = 1;
			for (int y = 0; y < N - 1; y++) {
				if (map[x][y].equals(map[x][y + 1])) {
					count++;
				} else {
					count = 1;
				}
				max = Math.max(count, max);
			}
		}

		for (int y = 0; y < N; y++) {
			int count = 1;
			for (int x = 0; x < N - 1; x++) {
				if (map[x][y].equals(map[x + 1][y])) {
					count++;
				} else {
					count = 1;
				}
				max = Math.max(count, max);
			}
		}

	}
}