-
Notifications
You must be signed in to change notification settings - Fork 0
/
P055_BJ16236_아기상어.java
111 lines (89 loc) · 2.48 KB
/
P055_BJ16236_아기상어.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Queue;
// bfs
public class P055_BJ16236_아기상어 {
static int N;
static Queue<int[]> point;
static int[][] arr;
static int[][] dist;
static ArrayList<int[]> fishes;
static int[] dx = {-1, 1, 0, 0};
static int[] dy = {0, 0, -1, 1};
static int answer;
static int baby = 2;
static void bfs() {
int level = 0;
while(!point.isEmpty()) { // bfs
int[] cur = point.poll(); // 상단에 있는 거 뽑기
for (int i = 0; i < 4; i++) {
int nx = cur[0] + dx[i];
int ny = cur[1] + dy[i];
if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;
if (dist[nx][ny] == 0 && arr[nx][ny] <= baby) { // 이동 가능성
dist[nx][ny] = dist[cur[0]][cur[1]] + 1;
point.offer(new int[] {nx, ny});
if (arr[nx][ny] >= 1 && arr[nx][ny] <= 6 && arr[nx][ny] < baby) { // 먹을 수 있을 경우
fishes.add(new int[] {nx, ny, dist[nx][ny]});
}
}
}
level++;
if (!fishes.isEmpty()) {
// 물고기 정렬
fishes.sort((int[] o1, int[] o2) -> {
if (o1[0] == o2[0]) return o1[1] - o1[2];
return o1[0] - o2[0];
});
int fishX = fishes.get(0)[0];
int fishY = fishes.get(0)[1];
answer += level;
arr[fishX][fishY] = 0; // 먹음
}
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
arr = new int[N][N];
dist = new int[N][N];
answer= 0;
int zero = 0;
// 입력
for (int i = 0; i < N; i++) {
String[] input = br.readLine().split(" ");
for (int j = 0; j < N; j++) {
arr[i][j] = Integer.parseInt(input[j]);
if (arr[i][j] == 9) { // 아기 상어 위치
point = new ArrayDeque<>();
point.offer(new int[] {i, j, 0}); // x, y
arr[i][j] = 0;
dist[i][j] = 0;
} else if (arr[i][j] == 0) zero++;
}
}
if (zero == N * N - 1) {
System.out.println(answer);
return;
}
int time = 0;
while(true) {
fishes = new ArrayList<>();
bfs();
if (fishes.size() == 0) {
System.out.println(time);
return;
}
// 물고기 정렬
fishes.sort((int[] o1, int[] o2) -> {
if (o1[0] == o2[0]) return o1[1] - o1[2];
return o1[0] - o2[0];
});
int[] current = fishes.remove(0);
time += dist[current[0]][current[1]];
baby++;
}
}
}