forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path2.java
92 lines (82 loc) Β· 2.84 KB
/
2.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
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
92
import java.util.*;
public class Main {
public static int n, m, result = 0;
public static int[][] arr = new int[8][8]; // μ΄κΈ° 맡 λ°°μ΄
public static int[][] temp = new int[8][8]; // λ²½μ μ€μΉν λ€μ 맡 λ°°μ΄
// 4κ°μ§ μ΄λ λ°©ν₯μ λν λ°°μ΄
public static int[] dx = {-1, 0, 1, 0};
public static int[] dy = {0, 1, 0, -1};
// κΉμ΄ μ°μ νμ(DFS)μ μ΄μ©ν΄ κ° λ°μ΄λ¬μ€κ° μ¬λ°©μΌλ‘ νΌμ§λλ‘ νκΈ°
public static void virus(int x, int y) {
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
// μ, ν, μ’, μ° μ€μμ λ°μ΄λ¬μ€κ° νΌμ§ μ μλ κ²½μ°
if (nx >= 0 && nx < n && ny >= 0 && ny < m) {
if (temp[nx][ny] == 0) {
// ν΄λΉ μμΉμ λ°μ΄λ¬μ€ λ°°μΉνκ³ , λ€μ μ¬κ·μ μΌλ‘ μν
temp[nx][ny] = 2;
virus(nx, ny);
}
}
}
}
// νμ¬ λ§΅μμ μμ μμμ ν¬κΈ° κ³μ°νλ λ©μλ
public static int getScore() {
int score = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (temp[i][j] == 0) {
score += 1;
}
}
}
return score;
}
// κΉμ΄ μ°μ νμ(DFS)μ μ΄μ©ν΄ μΈν리λ₯Ό μ€μΉνλ©΄μ, 맀 λ² μμ μμμ ν¬κΈ° κ³μ°
public static void dfs(int count) {
// μΈνλ¦¬κ° 3κ° μ€μΉλ κ²½μ°
if (count == 3) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
temp[i][j] = arr[i][j];
}
}
// κ° λ°μ΄λ¬μ€μ μμΉμμ μ ν μ§ν
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (temp[i][j] == 2) {
virus(i, j);
}
}
}
// μμ μμμ μ΅λκ° κ³μ°
result = Math.max(result, getScore());
return;
}
// λΉ κ³΅κ°μ μΈν리λ₯Ό μ€μΉ
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (arr[i][j] == 0) {
arr[i][j] = 1;
count += 1;
dfs(count);
arr[i][j] = 0;
count -= 1;
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = sc.nextInt();
}
}
dfs(0);
System.out.println(result);
}
}