-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path16236.java
More file actions
108 lines (99 loc) · 3.24 KB
/
Copy path16236.java
File metadata and controls
108 lines (99 loc) · 3.24 KB
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
// https://www.acmicpc.net/problem/16236
// 아기상어
import java.util.*;
import java.lang.*;
import java.io.*;
class Main {
static int n, map[][], x, y;
static int size = 2, eat = 0, answer = 0;
static final int[] DIRX = {-1, 0, 0, 1}, DIRY = {0, -1, 1, 0};
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(reader.readLine());
map = new int[n][n];
for(int i=0; i<n; i++){
StringTokenizer st = new StringTokenizer(reader.readLine());
for(int j=0; j<n; j++){
map[i][j] = Integer.parseInt(st.nextToken());
if(map[i][j] == 9){
x = i; y = j;
map[i][j] = 0;
}
}
}
long startTime = System.currentTimeMillis();
while(findAndEat(x, y)){
//print(map, x, y);
}
System.out.println(answer);
//System.out.println(System.currentTimeMillis()-startTime+"ms");
}
public static boolean findAndEat(int startx, int starty){
PriorityQueue<Node> que = new PriorityQueue<>();
boolean visited[][] = new boolean[n][n];
que.add(new Node(startx, starty, 0));
visited[startx][starty] = true;
while(!que.isEmpty()){
Node cur = que.poll();
//System.out.println(cur);
if(map[cur.x][cur.y] != 0 && map[cur.x][cur.y] < size){
x = cur.x; y = cur.y;
map[x][y] = 0;
eat++;
if(eat == size){
eat = 0;
size++;
}
answer += cur.depth;
return true;
}
for(int i=0; i<4; i++){
int x = cur.x + DIRX[i], y = cur.y + DIRY[i];
if(!check(x, y)) continue;
if(visited[x][y]) continue;
que.add(new Node(x, y, cur.depth+1));
visited[x][y] = true;
}
}
return false;
}
public static boolean check(int x, int y){
if(x < 0 || n <= x || y < 0 || n <= y)
return false;
if(map[x][y] > size)
return false;
return true;
}
public static void print(int[][] map, int x, int y){
StringBuilder sb = new StringBuilder();
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
if(i == x && j == y) sb.append('*');
else sb.append(map[i][j]);
sb.append(' ');
}sb.append('\n');
}System.out.println(sb);
}
}
class Node implements Comparable<Node> {
int x, y, depth;
public Node(int x, int y, int depth){
this.x = x;
this.y = y;
this.depth = depth;
}
@Override
public String toString(){
return x+", "+y+" : "+depth;
}
@Override
public int compareTo(Node o){
if(this.depth < o.depth) return -1;
else if(this.depth > o.depth) return 1;
else if(this.x < o.x) return -1;
else if(this.x > o.x) return 1;
else if(this.y < o.y) return -1;
else if(this.y > o.y) return 1;
else return 0;
}
}