Repository navigation
Expand file tree
/
Copy pathJW_131703.java
More file actions
51 lines (47 loc) ยท 1.96 KB
/
Copy pathJW_131703.java
File metadata and controls
51 lines (47 loc) ยท 1.96 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
public class JW_131703 {
public static void main(String[] args) {
int[][] beginning = { { 0, 1, 0, 0, 0 }, { 1, 0, 1, 0, 1 }, { 0, 1, 1, 1, 0 }, { 1, 0, 1, 1, 0 },
{ 0, 1, 0, 1, 0 } };
int[][] target = { { 0, 0, 0, 1, 1 }, { 0, 0, 0, 0, 1 }, { 0, 0, 1, 0, 1 }, { 0, 0, 0, 1, 0 },
{ 0, 0, 0, 0, 1 } };
System.out.println(solution(beginning, target));
}
static int n, m;
public static int solution(int[][] beginning, int[][] target) {
n = beginning.length;
m = beginning[0].length;
int min = Integer.MAX_VALUE;
// ๋ง๋ค ์ ์๋ ๋ชจ๋ ์กฐํฉ
// row๋ฅผ ๋ค์ง๋ ๊ฒฝ์ฐ์ ์
for (int i = 0; i < (1 << n); i++) {
// col์ ๋ค์ง๋ ๊ฒฝ์ฐ์ ์
for (int j = 0; j < (1 << m); j++) {
// ํด๋น ๋ค์ง๋ ๊ฒฝ์ฐ์ ์๋ก ๋ค์ง์์ ๋, ๋์ผํ๋ค๋ฉด
if (isPossible(beginning, target, i, j)) {
// ๋ค์ง์ ํ์
int cnt = Integer.bitCount(i) + Integer.bitCount(j);
min = Math.min(min, cnt); // ์ต์๊ฐ ๊ฐฑ์
}
}
}
return min == Integer.MAX_VALUE ? -1 : min;
}
private static boolean isPossible(int[][] beginning, int[][] target, int row, int col) {
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
int v = beginning[i][j]; // ๋ค์ง๊ธฐ ์ ์ ๊ฐ
// ๋ค์ง์ row์ ํด๋นํ๋ค๋ฉด
if (((1 << i) & row) != 0) {
v ^= 1; // ๋ค์ง๊ธฐ
}
// ๋ค์ง์ col์ ํด๋นํ๋ค๋ฉด
if (((1 << j) & col) != 0) {
v ^= 1; // ๋ค์ง๊ธฐ
}
// ๊ฒฐ๊ณผ๊ฐ target์ ํด๋น ๊ฐ๊ณผ ๋์ผํ์ง ์๋ค๋ฉด false ๋ฐํ
if (target[i][j] != v)
return false;
}
return true;
}
}