보호필름
in Algorithm on SW Expert Academy
Software Expert Academy [2112] 보호필름
풀이
- DFS
소스코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Solution {
static int D, W, K, ans;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
for (int tc = 1; tc <= T; tc++) {
StringTokenizer st = new StringTokenizer(br.readLine());
D = Integer.parseInt(st.nextToken());
W = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
ans = 987654321;
int[][] film = new int[D][W];
for (int i = 0; i < D; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < W; j++) {
film[i][j] = Integer.parseInt(st.nextToken());
}
}
chk(film, 0, 0);
System.out.println("#" + tc + " " + ans);
}
}
// A:0, B:1
public static void chk(int[][] film, int cnt, int idx) {
if (idx >= D) {
if (isOk(film)) {
ans = Math.min(cnt, ans);
}
return;
}
if (cnt >= ans)
return;
// 1. 그냥 가는 경우
chk(film, cnt, idx + 1);
// 2. A 투약
int[] originA = film[idx].clone();
Arrays.fill(film[idx], 0);
chk(film, cnt + 1, idx + 1);
film[idx] = originA;
// 3. B 투약
int[] originB = film[idx].clone();
Arrays.fill(film[idx], 1);
chk(film, cnt + 1, idx + 1);
film[idx] = originB;
}
public static boolean isOk(int[][] film) {
for (int j = 0; j < W; j++) {
int cnt = 0;
int pre = 0;
boolean flag = false;
for (int i = 0; i < D; i++) {
if (film[i][j] == pre) {
cnt++;
} else {
pre = film[i][j];
cnt = 1;
}
if (cnt >= K) {
flag = true;
break;
}
}
if (!flag) {
return false;
}
}
return true;
}
}