문제 출처
https://www.acmicpc.net/problem/1018
풀이
- 'W'로 먼저 시작하는 체스판과 'B'로 먼저 시작하는 체스판을 미리 만들고
입력받은 체스판과 비교해서 최솟값을 구하면 되는 문제이다.
- 체스판을 만들 때는 flag를 잘 활용한다.
- 중요한 부분은 이중 for문을 선언할 때 index를 잘 체크해주어야 한다.
x는 x+9 <= N 까지 증가할 수 있고, y는 y+9 <= M 까지 증가할 수 있다.
(N, M이 8보다 큰 경우 체스판을 움직이면서 체크하기 위함)
코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer stringTokenizer = new StringTokenizer(bufferedReader.readLine());
int N = Integer.parseInt(stringTokenizer.nextToken());
int M = Integer.parseInt(stringTokenizer.nextToken());
char[][] board = new char[N][M];
for (int i = 0; i < N; i++) {
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
String row = stringTokenizer.nextToken();
for (int j = 0; j < M; j++) {
char[] rowToCharArray = row.toCharArray();
board[i][j] = rowToCharArray[j];
}
}
char[][] whiteBoard = new char[8][8];
char[][] blackBoard = new char[8][8];
int flag = 1;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
whiteBoard[i][j] = flag == 1 ? 'W' : 'B';
flag *= -1;
blackBoard[i][j] = flag == 1 ? 'W' : 'B';
}
flag *= -1;
}
int answer = Integer.MAX_VALUE;
int x = 0, y = 0;
while (true) {
int whiteResult = 0;
int blackResult = 0;
for (int i = x; i < x + 8; i++) {
for (int j = y; j < y + 8; j++) {
if (board[i][j] != whiteBoard[i - x][j - y]) {
whiteResult++;
}
if (board[i][j] != blackBoard[i - x][j - y]) {
blackResult++;
}
}
}
int resultMinValue = Math.min(whiteResult, blackResult);
answer = Math.min(answer, resultMinValue);
if ((y + 1) + 8 <= M) {
y++;
} else {
if ((x + 1) + 8 <= N) {
x++;
y = 0;
} else {
break;
}
}
}
System.out.println(answer);
}
}
채점 결과