|
| 1 | +import java.io.BufferedReader; |
| 2 | +import java.io.IOException; |
| 3 | +import java.io.InputStreamReader; |
| 4 | +import java.util.PriorityQueue; |
| 5 | +import java.util.StringTokenizer; |
| 6 | + |
| 7 | +public class JM_2151 { |
| 8 | + static class Point implements Comparable<Point> { |
| 9 | + int y, x; |
| 10 | + int dir; |
| 11 | + int dist; |
| 12 | + |
| 13 | + public Point(int y, int x, int dir, int dist) { |
| 14 | + this.y = y; |
| 15 | + this.x = x; |
| 16 | + this.dir = dir; |
| 17 | + this.dist = dist; |
| 18 | + } |
| 19 | + |
| 20 | + @Override |
| 21 | + public int compareTo(Point o) { |
| 22 | + return this.dist - o.dist; |
| 23 | + } |
| 24 | + } |
| 25 | + static int N; |
| 26 | + static char[][] map; |
| 27 | + static Point start; |
| 28 | + static Point end; |
| 29 | + static final int[][] DIR = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}}; |
| 30 | + |
| 31 | + private static boolean inRange(int y, int x) { |
| 32 | + return 0 <= y && y < N && 0 <= x && x < N; |
| 33 | + } |
| 34 | + |
| 35 | + private static int solve() { |
| 36 | + PriorityQueue<Point> pq = new PriorityQueue<>(); |
| 37 | + boolean[][][] visited = new boolean[N][N][4]; |
| 38 | + |
| 39 | + for (int i = 0; i < 4; i++) { |
| 40 | + pq.add(new Point(start.y, start.x, i, 0)); |
| 41 | + } |
| 42 | + |
| 43 | + while (!pq.isEmpty()) { |
| 44 | + Point curr = pq.poll(); |
| 45 | + |
| 46 | + visited[curr.y][curr.x][curr.dir] = true; |
| 47 | + |
| 48 | + if(curr.y == end.y && curr.x == end.x) return curr.dist; |
| 49 | + |
| 50 | + int ny = curr.y + DIR[curr.dir][0]; |
| 51 | + int nx = curr.x + DIR[curr.dir][1]; |
| 52 | + |
| 53 | + if(!inRange(ny, nx) || map[ny][nx] == '*' || visited[ny][nx][curr.dir]) continue; |
| 54 | + |
| 55 | + if(map[ny][nx] == '!') { |
| 56 | + pq.add(new Point(ny, nx, (curr.dir + 1) % 4, curr.dist + 1)); |
| 57 | + pq.add(new Point(ny, nx, (curr.dir + 3) % 4, curr.dist + 1)); |
| 58 | + } |
| 59 | + pq.add(new Point(ny, nx, curr.dir, curr.dist)); |
| 60 | + |
| 61 | + } |
| 62 | + |
| 63 | + return -1; |
| 64 | + } |
| 65 | + |
| 66 | + public static void main(String[] args) throws IOException { |
| 67 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 68 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 69 | + N = Integer.parseInt(st.nextToken()); |
| 70 | + |
| 71 | + map = new char[N][N]; |
| 72 | + for (int i = 0; i < N; i++) { |
| 73 | + map[i] = br.readLine().toCharArray(); |
| 74 | + for (int j = 0; j < N; j++) { |
| 75 | + if(map[i][j] == '#') { |
| 76 | + if(start == null) start = new Point(i, j, -1, 0); |
| 77 | + else end = new Point(i, j, -1, 0); |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + System.out.println(solve()); |
| 83 | + } |
| 84 | +} |
0 commit comments