[BaekJoon] 1018번 - 체스판 다시 칠하기 [Java][C++]
[BaekJoon] 1018번 - 체스판 다시 칠하기 [Java][C++]
1. 문제 풀이
주어진 보드에서 8×8 크기의 체스판을 만들 때 가장 색상을 다시 덜 칠해도 되는 횟수를 구하는 문제로 브루트 포스로 탐색하면 해결할 수 있다. 8×8 크기의 체스판의 시작점을 보드 전체를 순회하며 잡고 각 체스판마다 맨 왼쪽 위 칸을 흰색으로 두는 경우 칠하는 횟수와 검은색으로 두는 경우 칠하는 횟수를 세서 전체 보드에 대한 최솟값을 찾으면 된다.
2. 코드
1. 풀이 [Java]
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
import java.io.*;
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[][] board = new char[N][M];
for (int i = 0; i < N; i++) {
board[i] = br.readLine().toCharArray();
}
int min = 32;
for (int r = 0; r <= N - 8; r++) {
for (int c = 0; c <= M - 8; c++) {
int isWhite = 0; // 맨 왼쪽 위 칸을 흰색으로 둘 경우
int isBlack = 0; // 맨 왼쪽 위 칸을 검은색으로 둘 경우
for (int i = r; i < r + 8; i++) {
for (int j = c; j < c + 8; j++) {
if ((i + j) % 2 == 0) {
if (board[i][j] == 'B') {
isWhite++;
} else {
isBlack++;
}
} else {
if (board[i][j] == 'W') {
isWhite++;
} else {
isBlack++;
}
}
}
}
min = Math.min(min, Math.min(isWhite, isBlack));
}
}
System.out.println(min);
}
}
2. 풀이 [C++]
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
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<string> v(n);
for (string& x : v) cin >> x;
int mn = 32;
for (int r = 0; r <= n - 8; r++) {
for (int c = 0; c <= m - 8; c++) {
int isWhite = 0; // 맨 왼쪽 위 칸을 흰색으로 둘 경우
int isBlack = 0; // 맨 왼쪽 위 칸을 검은색으로 둘 경우
for (int i = r; i < r + 8; i++) {
for (int j = c; j < c + 8; j++) {
if ((i + j) % 2 == 0) {
if (v[i][j] == 'B') {
isWhite++;
} else {
isBlack++;
}
} else {
if (v[i][j] == 'W') {
isWhite++;
} else {
isBlack++;
}
}
}
}
mn = min(mn, min(isWhite, isBlack));
}
}
cout << mn;
}
This post is licensed under CC BY 4.0 by the author.