-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path16236
147 lines (113 loc) · 2.84 KB
/
16236
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import java.io.IOException;
import java.util.*;
class pos{
int x, y;
pos(int x, int y){
this.x = x;
this.y = y;
}
}
public class Main {
public static int[] dx = {0, 0, 1, -1};
public static int[] dy = {-1, 1, 0, 0};
public static int[][] feed = new int[20][20];
public static int[][] check;
public static int[] sp = new int[2];
public static int shark_size = 2;
public static int md, mx, my;
public static void bfs(int x, int y) {
Queue<pos> q = new LinkedList<pos>();
check[x][y] = 0;
q.add(new pos(x, y));
while(!q.isEmpty()) {
pos now = q.poll();
for(int i=0; i<4; i++) {
int fx = now.x + dx[i];
int fy = now.y + dy[i];
// 맵 범위 넘어선 경우
if(fx>=check.length || fx<0 || fy>=check.length || fy<0)
continue;
// 상어보다 물고기가 큰 경우, 이미 지난 좌표일 경우
if(feed[fx][fy]>shark_size || check[fx][fy]!=-1)
continue;
// 한칸 이동해서 +1
check[fx][fy] = check[now.x][now.y] + 1;
//체크
// System.out.println(fx+", "+fy+"에서 +1해서" +check[fx][fy]);
// 상어가 물고기 먹을경우
if(feed[fx][fy]<shark_size && feed[fx][fy]!=0) {
if(check[fx][fy] < md) {
mx = fx;
my = fy;
md = check[fx][fy];
}
else if(check[fx][fy] == md) {
if(mx == fx) {
if(my>fy) {
mx = fx;
my = fy;
}
}else if(mx>fx) {
mx = fx;
my = fy;
}
}
}
q.add(new pos(fx, fy));
}
}
}
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
// bfs 체크용
check = new int[size][size];
for(int i=0; i<size; i++) {
for(int j=0; j<size; j++) {
feed[i][j] = sc.nextInt();
if(feed[i][j] == 9) {
sp[0] = i;
sp[1] = j;
feed[i][j] = 0;
}
}
}
/*
* //체크 for(int i=0; i<size; i++) { for(int j=0; j<size; j++)
* System.out.print(feed[i][j]+" "); System.out.println(); }
* System.out.println(sp[0] +" "+sp[1]+"이 상어위치");
*/
int cnt = 0;
int time = 0;
while(true) {
// bfs 시작할때마다 초기화
for(int i=0; i<check.length; i++) {
for(int j=0; j<check.length; j++)
check[i][j] = -1;
}
md = check.length*check.length + 1;
mx = check.length;
my = check.length;
//체크
// System.out.println(sp[0]+", "+sp[1]+"로 bfs시작");
bfs(sp[0], sp[1]);
if(mx != check.length && my != check.length) {
//체크
// System.out.println(mx +", "+my+"에서 상어가 물고기 먹음");
time += check[mx][my];
sp[0] = mx;
sp[1] = my;
feed[mx][my] = 0;
cnt++;
if(cnt == shark_size) {
cnt = 0;
shark_size++;
}
}
else
break;
}
System.out.println(time);
sc.close();
}
}