-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathDH_131703.java
More file actions
91 lines (72 loc) ยท 2.94 KB
/
DH_131703.java
File metadata and controls
91 lines (72 loc) ยท 2.94 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.util.*;
/*
* 2์ฐจ์ ๋์ ๋ค์ง๊ธฐ
*/
public class DH_131703 {
static final int INF = Integer.MAX_VALUE;
static int result = INF;
static boolean[] sel;
static int solution(int[][] beginning, int[][] target) {
int r = beginning.length, c = beginning[0].length;
int size = r + c;
sel = new boolean[size];
// beginning๊ณผ target๋ฅผ ๋น๊ตํ๋ฉด์ ๊ฐ์ด ๋ค๋ฅธ ์ขํ๋ฅผ set์ ์ ์ฅํจ
HashSet<Integer> set = getDiffPointIdx(beginning, target);
// ๋ชจ๋ ํ๊ณผ ์ด์ ๋ํด ๋ค์ง์ด๋ณด๊ธฐ
// ํ, ์ด์ ๋ํด (๋ค์ง๋๋ค / ๋ค์ง์ง ์๋๋ค) ๋ ๊ฐ์ง์ ๊ฒฝ์ฐ๊ฐ ์์ผ๋ฏ๋ก powerset ์ด์ฉ
powerSet(0, 0, beginning, target, set);
return result == INF ? - 1: result;
}
static void powerSet(int idx, int cnt, int[][] b, int[][] t, HashSet<Integer> set) {
if(idx == sel.length) return;
// ๋ค์ง๊ธฐ
sel[idx] = true;
b = flipMap(idx, b.length, b, t, set);
if(set.isEmpty()) result = Math.min(result, cnt + 1);
powerSet(idx + 1, cnt + 1, b, t, set);
// ์์๋ณต๊ตฌ ํ๊ธฐ
sel[idx] = false;
b = flipMap(idx, b.length, b, t, set);
if(set.isEmpty()) result = Math.min(result, cnt);
powerSet(idx + 1, cnt, b, t, set);
}
// beginning๊ณผ target๋ฅผ ๋น๊ตํ๋ฉด์ ๊ฐ์ด ๋ค๋ฅธ ์ขํ๋ฅผ set์ ์ ์ฅํจ
static HashSet<Integer> getDiffPointIdx(int[][] beginning, int[][] target) {
HashSet<Integer> set = new HashSet<>();
int r = beginning.length, c = beginning[0].length;
for(int br = 0; br < r; br++) {
for(int bc = 0; bc < c; bc++) {
if(beginning[br][bc] != target[br][bc]) {
// 2์ฐจ์ ์ขํ๋ฅผ 1์ฐจ์์ผ๋ก ๋ณํํ์ฌ set์ ์ ์ฅ
int idx = br * c + bc;
set.add(idx);
}
}
}
return set;
}
// i: ๋ค์ง๋ ํ/์ด์ ๋ฒํธ
static int[][] flipMap(int i, int r, int[][] b, int[][] t, HashSet<Integer> set) {
// i๊ฐ ํ์ ๊ฐ์๋ณด๋ค ํฌ๋ค๋ฉด ์ด์ ๋ค์ง์ด์ผ ๋จ
if(i < r) {
// ์ง์ ๋ ํ, ์ด์ ๋ํด 0-1 ๋ฐ์ (1๊ณผ XOR ์ฐ์ฐ)
for(int bc = 0; bc < b[0].length; bc++) {
b[i][bc] ^= 1;
// ์ขํ ๋น๊ตํด์ set ์
๋ฐ์ดํธ ํด์ฃผ๊ธฐ
int idx = i * b[0].length + bc;
if(b[i][bc] == t[i][bc]) if(set.contains(idx)) set.remove(idx);
else set.add(idx);
}
} else {
// ์ง์ ๋ ํ, ์ด์ ๋ํด 0-1 ๋ฐ์ (1๊ณผ XOR ์ฐ์ฐ)
for(int br = 0; br < b.length; br++) {
b[br][i - r] ^= 1;
// ์ขํ ๋น๊ตํด์ set ์
๋ฐ์ดํธ ํด์ฃผ๊ธฐ
int idx = br * b[0].length + (i - r);
if(b[br][i - r] == t[br][i - r]) if(set.contains(idx)) set.remove(idx);
else set.add(idx);
}
}
return b;
}
}