문제
지민이는 자신의 저택에서 MN개의 단위 정사각형으로 나누어져 있는 M×N 크기의 보드를 찾았다. 어떤 정사각형은 검은색으로 칠해져 있고, 나머지는 흰색으로 칠해져 있다. 지민이는 이 보드를 잘라서 8×8 크기의 체스판으로 만들려고 한다.
체스판은 검은색과 흰색이 번갈아서 칠해져 있어야 한다. 구체적으로, 각 칸이 검은색과 흰색 중 하나로 색칠되어 있고, 변을 공유하는 두 개의 사각형은 다른 색으로 칠해져 있어야 한다. 따라서 이 정의를 따르면 체스판을 색칠하는 경우는 두 가지뿐이다. 하나는 맨 왼쪽 위 칸이 흰색인 경우, 하나는 검은색인 경우이다.
보드가 체스판처럼 칠해져 있다는 보장이 없어서, 지민이는 8×8 크기의 체스판으로 잘라낸 후에 몇 개의 정사각형을 다시 칠해야겠다고 생각했다. 당연히 8*8 크기는 아무데서나 골라도 된다. 지민이가 다시 칠해야 하는 정사각형의 최소 개수를 구하는 프로그램을 작성하시오.
입력
첫째 줄에 N과 M이 주어진다. N과 M은 8보다 크거나 같고, 50보다 작거나 같은 자연수이다. 둘째 줄부터 N개의 줄에는 보드의 각 행의 상태가 주어진다. B는 검은색이며, W는 흰색이다.
출력
첫째 줄에 지민이가 다시 칠해야 하는 정사각형 개수의 최솟값을 출력한다.
8*8 체스판에 칠한다는 걸 간과해서 처음에는 답이 다르게 나왔었다
M, N과 8의 차이만큼 체스판을 옮겨가며 최소값을 구해야 하는 문제이다.
좀 더 간단하게 구현할 수 있을 것 같지만, 일단 두 개의 케이스를 각각 배열로 구현해두고, 주어진 배열에서 다른 값의 개수를 세며 더 적은 값을 출력하도록 하였다.
package BOJ0729;
import java.util.Scanner;
public class BOJ_1018_ColorChess {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int M = sc.nextInt();
String[][] chess = new String[N][M];
String[][] case1 = new String[N][M]; // W로 시작
String[][] case2 = new String[N][M]; // B로 시작
for (int i = 0; i < N; i++) {
chess[i] = sc.next().split("");
}
// case 1
for (int r = 0; r < 8; r++)
for (int c = 0; c < 8; c++) {
if ((r + c) % 2 == 0) {
case1[r][c] = "W";
case2[r][c] = "B";
} else {
case1[r][c] = "B";
case2[r][c] = "W";
}
}
// 각각 다른 개수를 출력
int cnt1 = 0;
int cnt2 = 0;
int min = M * N;
int disr = N - 8;
int disc = M - 8;
for (int dr = 0; dr <= disr; dr++) {
for (int dc = 0; dc <= disc; dc++) {
for (int r = 0; r < 8; r++) {
for (int c = 0; c < 8; c++) {
String str = chess[dr + r][dc + c];
if (!str.equals(case1[r][c])) {
cnt1++;
}
if (!str.equals(case2[r][c])) {
cnt2++;
}
}
}
int tmp = Math.min(cnt1, cnt2);
if (tmp < min)
min = tmp;
cnt1 = 0;
cnt2 = 0;
}
}
System.out.println(min);
}
}
'문제 풀이 > BOJ' 카테고리의 다른 글
[백준] 15649 - N과 M (1) (자바/Java) 백트래킹 DFS (0) | 2022.08.03 |
---|---|
[백준] 1436 - 영화감독 숌 (자바/Java) (0) | 2022.07.31 |
[백준] 7568 - 덩치 (자바/Java) (0) | 2022.07.29 |
[백준] 11729 - 하노이 탑 이동순서 (자바/Java): 하노이 타워(Towers of Hanoi) (0) | 2022.07.29 |
[백준] 2447 - 별 찍기 10 (자바/Java): 재귀 (0) | 2022.07.29 |