문제
상근이는 어렸을 적에 "봄보니 (Bomboni)" 게임을 즐겨했다.
가장 처음에 N×N크기에 사탕을 채워 놓는다. 사탕의 색은 모두 같지 않을 수도 있다. 상근이는 사탕의 색이 다른 인접한 두 칸을 고른다. 그 다음 고른 칸에 들어있는 사탕을 서로 교환한다. 이제, 모두 같은 색으로 이루어져 있는 가장 긴 연속 부분(행 또는 열)을 고른 다음 그 사탕을 모두 먹는다.
사탕이 채워진 상태가 주어졌을 때, 상근이가 먹을 수 있는 사탕의 최대 개수를 구하는 프로그램을 작성하시오.
입력
첫째 줄에 보드의 크기 N이 주어진다. (3 ≤ N ≤ 50)
다음 N개 줄에는 보드에 채워져 있는 사탕의 색상이 주어진다. 빨간색은 C, 파란색은 P, 초록색은 Z, 노란색은 Y로 주어진다.
사탕의 색이 다른 인접한 두 칸이 존재하는 입력만 주어진다.
출력
첫째 줄에 상근이가 먹을 수 있는 사탕의 최대 개수를 출력한다.
제한
- 시간 제한 : 1초
- 메모리 제한 : 128MB
문제 풀이 과정
하나씩 사탕의 위치를 바꿔보면서, 갯수를 세주면 된다.
정답 코드
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Main3085 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
char[][] map = new char[N][N];
for (int i = 0; i < N; i++) {
String input = br.readLine();
for (int j = 0; j < N; j++) {
map[i][j] = input.charAt(j);
}
}
int max = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (j + 1 < N) {
swap(map, i, j, i, j + 1);
max = Math.max(check(map), max);
swap(map, i, j, i, j + 1);
}
if (i + 1 < N) {
swap(map, i, j, i + 1, j);
max = Math.max(check(map), max);
swap(map, i, j, i + 1, j);
}
}
}
System.out.println(max);
}
private static int check(char[][] map) {
int result = 0;
for (int i = 0; i < map.length; i++) {
int cnt = 1;
for (int j = 1; j < map[0].length; j++) {
if (map[i][j] == map[i][j - 1]) {
cnt++;
} else {
cnt = 1;
}
if (result < cnt) {
result = cnt;
}
}
cnt = 1;
for (int j = 1; j < map.length; j++) {
if (map[j][i] == map[j - 1][i]) {
cnt++;
} else {
cnt = 1;
}
if (result < cnt) {
result = cnt;
}
}
}
return result;
}
private static void swap(char[][] map, int i, int j, int toI, int toJ) {
char tmp = map[i][j];
map[i][j] = map[toI][toJ];
map[toI][toJ] = tmp;
}
}