Algorithm/JAVA - BOJ

BOJ/백준 - 1018 체스판 다시 칠하기 JAVA

ㅇㅇ잉 2021. 8. 13. 20:31

체스판의 크기가 8*8이고,

맨 윗칸이 첫번째가 흰색인 경우/맨 윗칸이 첫번째가 검은색인 경우로 나누어 생각했다.

일단 최악의 경우는 전부 바꾸게 되어 64가 될 것이고,

find함수로 첫번째가 B가 될 경우와 W가 될 경우를 나누어서 생각해보았다.

그렇게 받은 N x M 체스판을 전부 검사해보면 끝~!

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
 
public class Main {
 
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 
 
        StringTokenizer st = new StringTokenizer(br.readLine());
 
        int N = Integer.parseInt(st.nextToken());
        int M = Integer.parseInt(st.nextToken());
        char[][] arr = new char[N][M];
 
        for(int i=0;i<N;i++){
            arr[i] = br.readLine().toCharArray();
        }
 
        int result=64;
        for(int n=0;n<N-7;n++){
            for(int m=0;m<M-7;m++){
                int cnt = find(n,m,arr);
                cnt = Math.min(cnt,64-cnt);
                result = Math.min(result,cnt);
            }
        }
        System.out.println(result);
 
    }
 
    public static int find(int n, int m,char[][] arr){
        int cnt=0;
        for(int i=0;i<8;i++) {
            for (int j = 0; j < 8; j++) {
                if (i % 2 == 0) {
                    if (j % 2 == 0 && arr[n + i][m + j] == 'B') cnt++;
                    else if (j % 2 == 1 && arr[n + i][m + j] == 'W') cnt++;
                } else {
                    if (j % 2 == 0 && arr[n + i][m + j] == 'W') cnt++;
                    else if (j % 2 == 1 && arr[n + i][m + j] == 'B') cnt++;
                }
            }
        }
        return cnt;
    }
}
cs