
문제 링크
https://www.acmicpc.net/problem/1018
접근 방법
8x8 체스판을 만들 수 있는 모든 구간을 탐색하면서, 시작 색을 W 또는 B로 설정해 각각 다시 칠해야 하는 칸의 수를 계산하고, 그중 최소값을 구합니다.
소스 코드
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.IOException;
public class Main {
static String[] board;
public static int countRepaint(int row, int col, char startColor) {
int count = 0;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
char expectedColor = ((i + j) % 2 == 0) ? startColor : (startColor == 'W' ? 'B' : 'W');
if (board[row + i].charAt(col + j) != expectedColor) {
count++;
}
}
}
return count;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int y = Integer.parseInt(st.nextToken());
int x = Integer.parseInt(st.nextToken());
board = new String[y];
for (int i = 0; i < y; i++) {
board[i] = br.readLine();
}
int min = Integer.MAX_VALUE;
for (int i = 0; i <= y - 8; i++) {
for (int j = 0; j <= x - 8; j++) {
int repaintW = countRepaint(i, j, 'W');
int repaintB = countRepaint(i, j, 'B');
min = Math.min(min, Math.min(repaintW, repaintB));
}
}
System.out.println(min);
}
}
코드 설명
8x8 크기의 체스판을 만들 수 있는 위치마다 countRepaint()를 호출해 다시 칠해야 하는 칸의 수를 구합니다.
이때 시작 색을 W로 했을 때와 B로 했을 때를 모두 비교해, 두 값 중 더 적게 칠하는 쪽을 선택합니다.
최종적으로 가장 적게 칠한 경우의 수를 출력합니다.
'코딩테스트 > 백준' 카테고리의 다른 글
| [백준 JAVA] 20920. 영단어 암기는 괴로워 (1) | 2025.08.06 |
|---|---|
| [백준 JAVA] 14888. 연산자 끼워넣기 (0) | 2025.07.31 |
| [백준 JAVA] 9663. N-Queen (0) | 2025.07.27 |
| [백준 JAVA] 15683. 감시 (0) | 2025.07.21 |
| [백준 JAVA] 4779. 칸토어 집합 (0) | 2025.07.18 |