백준/브루트포스
[백준] 3085 - 사탕 게임 [JAVA]
odong2
2024. 5. 8. 16:34

코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int max = Integer.MIN_VALUE;
static int N;
static char[][] board;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
board = new char[N][N];
// 입력값 초기화
for (int i = 0; i < N; i++) {
String str = br.readLine();
for (int j = 0; j < N; j++) {
board[i][j] = str.charAt(j);
}
}
// 행 기준 가로로 위치 변경 후 탐색
for (int x = 0; x < N; x++) {
for (int y = 0; y < N - 1; y++) {
swap(x, y, x, y + 1);
search();
swap(x, y + 1, x, y); // 원상태 복구
}
}
// 열 기준 세로로 위치 변경 후 탐색
for (int x = 0; x < N - 1; x++) {
for (int y = 0; y < N; y++) {
swap(x, y, x + 1, y);
search();
swap(x + 1, y, x, y); // 원상태 복구
}
}
System.out.println(max);
}
// 위치 교환
static void swap(int x1, int y1, int x2, int y2) {
char temp = board[x1][y1];
board[x1][y1] = board[x2][y2];
board[x2][y2] = temp;
}
// max 값 조회
static void search() {
// 행 조회
for (int x = 0; x < N; x++) {
int count = 1;
for (int y = 0; y < N - 1; y++) {
if (board[x][y] == board[x][y + 1]) {
max = Math.max(++count, max);
}
else count = 1;
}
}
// 열 조회
for (int y = 0; y < N; y++) {
int count = 1;
for (int x = 0; x < N - 1; x++) {
if (board[x][y] == board[x + 1][y]) {
max = Math.max(++count, max);
}
else count = 1;
}
}
}
}