-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathB.java
More file actions
68 lines (63 loc) · 2.31 KB
/
Copy pathB.java
File metadata and controls
68 lines (63 loc) · 2.31 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
package atcoder.grand_44;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Scanner;
public final class B {
private static final int[][] DIRS = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
public static void main(String[] args) {
final Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
final int n = in.nextInt();
final boolean[][] matrix = new boolean[n][n];
in.nextLine();
final int[] exits = new int[n * n];
for (int i = 0; i < n * n; i++) {
exits[i] = in.nextInt();
}
final Map<Integer, int[]> map = new HashMap<>();
int curr = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = true;
map.put(curr++, new int[] { i, j });
}
}
int res = 0;
Integer[][] dp = new Integer[n][n];
for (int exit : exits) {
final int[] pos = map.get(exit);
res += shortestPath(matrix, pos[0], pos[1], dp);
}
System.out.println(res);
}
private static int shortestPath(boolean[][] matrix, int r, int c, Integer[][] dp) {
final int n = matrix.length;
final PriorityQueue<int[]> deque = new PriorityQueue<>(Comparator.comparingInt(a -> a[2]));
final boolean[][] visited = new boolean[n][n];
deque.offer(new int[] { r, c, 0 });
matrix[r][c] = false;
while (!deque.isEmpty()) {
final int[] curr = deque.remove();
if (dp[curr[0]][curr[1]] != null) {
return dp[curr[0]][curr[1]];
}
if (curr[0] == 0 || curr[0] == n - 1 || curr[1] == 0 || curr[1] == n - 1) {
dp[r][c] = curr[2];
return curr[2];
}
if (visited[curr[0]][curr[1]]) {
continue;
}
visited[curr[0]][curr[1]] = true;
for (int[] dir : DIRS) {
final int nx = dir[0] + curr[0];
final int ny = dir[1] + curr[1];
deque.offer(new int[] { nx, ny, curr[2] + (matrix[nx][ny] ? 1 : 0) });
}
}
return -1;
}
}