104 lines
2.5 KiB
Java
104 lines
2.5 KiB
Java
import java.util.*;
|
|
|
|
class Point {
|
|
int x, y;
|
|
|
|
Point(int x, int y) {
|
|
this.x = x;
|
|
this.y = y;
|
|
}
|
|
}
|
|
|
|
class Node extends Point {
|
|
int dist;
|
|
|
|
Node(int dist, int x, int y) {
|
|
super(x, y);
|
|
this.dist = dist;
|
|
}
|
|
}
|
|
|
|
public class _16236 {
|
|
static boolean inField(int x, int y, int N) {
|
|
return (0<=x && x<N) && (0<=y && y<N);
|
|
}
|
|
public static void main(String[] args) {
|
|
Scanner sc = new Scanner(System.in);
|
|
int N = sc.nextInt();
|
|
|
|
int[][] field = new int[N][N];
|
|
Point shark = new Point(0, 0);
|
|
|
|
for(int i=0; i<N; i++) {
|
|
for(int j=0; j<N; j++) {
|
|
field[i][j] = sc.nextInt();
|
|
|
|
if(field[i][j]==9) {
|
|
shark.x = j;
|
|
shark.y = i;
|
|
field[i][j] = 0;
|
|
}
|
|
}
|
|
}
|
|
|
|
sc.close();
|
|
|
|
int sharkSize = 2;
|
|
int eatCount = 0;
|
|
int moveTime = 0;
|
|
|
|
PriorityQueue<Node> pq = new PriorityQueue<>((a, b) -> {
|
|
if(a.dist == b.dist) {
|
|
if(a.y == b.y) return a.x - b.x;
|
|
return a.y - b.y;
|
|
}
|
|
return a.dist - b.dist;
|
|
});
|
|
|
|
int[] dx = {0,-1,1,0};
|
|
int[] dy = {-1,0,0,1};
|
|
|
|
while(true) {
|
|
boolean[][] visited = new boolean[N][N];
|
|
boolean eatFish = false;
|
|
pq.clear();
|
|
visited[shark.y][shark.x] = true;
|
|
pq.add(new Node(0, shark.x, shark.y));
|
|
|
|
while(!pq.isEmpty()) {
|
|
Node now = pq.poll();
|
|
|
|
if(field[now.y][now.x] != 0 && field[now.y][now.x] < sharkSize) {
|
|
field[now.y][now.x] = 0;
|
|
shark.x = now.x;
|
|
shark.y = now.y;
|
|
eatCount++;
|
|
moveTime += now.dist;
|
|
eatFish = true;
|
|
|
|
if(sharkSize == eatCount) {
|
|
eatCount = 0;
|
|
sharkSize++;
|
|
}
|
|
|
|
break;
|
|
}
|
|
|
|
for(int i=0; i<4; i++) {
|
|
int nx = now.x + dx[i];
|
|
int ny = now.y + dy[i];
|
|
|
|
if(inField(nx, ny, N) && !visited[ny][nx] && field[ny][nx] <= sharkSize) {
|
|
pq.add(new Node(now.dist + 1, nx, ny));
|
|
visited[ny][nx] = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
if(!eatFish) break;
|
|
}
|
|
|
|
System.out.println(moveTime);
|
|
}
|
|
}
|