[Link] https://www.acmicpc.net/problem/3190
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
#include <algorithm>
#include <iostream>
#include <vector>
#include <queue>
// #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF = 987654321;
int n, m, ans = 0, time = 0, shark_len = 2, ate_fish = 0, ci, cj, elapse;
int map[500][500];
bool visit[500][500];
struct point {
int i, j, dis;
point(int i, int j, int dis) : i(i), j(j), dis(dis) {};
};
int di[] = { -1, 0, 0, 1 };
int dj[] = { 0, -1, 1, 0 };
void bfs() {
queue<point> q;
q.push(point(ci, cj, 0));
int close_i = INF, close_j = INF, min_dis = INF;
elapse = 0;
while(!q.empty()) {
point p = q.front();
q.pop();
if(visit[p.i][p.j]) continue;
visit[p.i][p.j] = true;
if(map[p.i][p.j] && map[p.i][p.j] < shark_len) {
if(p.dis < min_dis) {
close_i = p.i;
close_j = p.j;
min_dis = p.dis;
} else if(p.dis == min_dis) {
if(close_i == p.i) close_j = min(close_j, p.j);
else if(close_i > p.i) {
close_i = p.i;
close_j = p.j;
}
}
}
for(int i = 0; i < 4; i++) {
int ii = p.i + di[i], jj = p.j + dj[i];
if(ii < 0 || jj < 0 || ii >= n || jj >= n || visit[ii][jj]) continue;
if(map[ii][jj] > shark_len) continue;
q.push(point(ii, jj, p.dis + 1));
}
}
for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) visit[i][j] = false;
if(close_i == INF) return;
if(++ate_fish == shark_len) shark_len++, ate_fish = 0;
ci = close_i, cj = close_j, elapse = min_dis;
map[ci][cj] = 0;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> n;
time = 0;
for(int i = 0; i < n; i++) {
int fish = 0;
for(int j = 0; j < n; j++) {
int in; cin >> in;
if(in == 9) ci = i , cj = j;
else {
map[i][j] = in;
fish++;
}
}
}
while(1) {
int si = ci, sj = cj;
bfs();
if(ci == si && cj == sj) break;
time += elapse;
}
cout << time;
return 0;
}