|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | +class Solution { |
| 4 | + static int[][] dir = new int[][]{{1,0}, {-1,0}, {0,1}, {0,-1}}; |
| 5 | + static int answer = -1; |
| 6 | + static Point start, target; |
| 7 | + static int N, M; |
| 8 | + static char[][] map; |
| 9 | + static int[][] visited; |
| 10 | + |
| 11 | + public int solution(String[] board) { |
| 12 | + N = board.length; |
| 13 | + M = board[0].length(); |
| 14 | + map = new char[N][M]; |
| 15 | + visited = new int[N][M]; |
| 16 | + for (int i = 0; i < N; i++) { |
| 17 | + map[i] = board[i].toCharArray(); |
| 18 | + Arrays.fill(visited[i], Integer.MAX_VALUE); |
| 19 | + for (int j = 0; j < M; j++) { |
| 20 | + if (map[i][j] == 'R') start = new Point(i, j, 0); |
| 21 | + else if (map[i][j] == 'G') target = new Point(i, j, 0); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + bfs(); |
| 26 | + |
| 27 | + return answer; |
| 28 | + } |
| 29 | + |
| 30 | + private void bfs() { |
| 31 | + Queue<Point> q = new LinkedList<>(); |
| 32 | + q.add(new Point(start.y, start.x, start.cnt)); |
| 33 | + visited[start.y][start.x] = 0; |
| 34 | + while (!q.isEmpty()) { |
| 35 | + Point curr = q.poll(); |
| 36 | + if (curr.y == target.y && curr.x == target.x) { |
| 37 | + answer = curr.cnt; |
| 38 | + return; |
| 39 | + } |
| 40 | + |
| 41 | + for (int[] d : dir) { |
| 42 | + int ny = curr.y, nx = curr.x; |
| 43 | + while (true) { |
| 44 | + ny += d[0]; |
| 45 | + nx += d[1]; |
| 46 | + if (ny < 0 || ny >= N || nx < 0 || nx >= M || map[ny][nx] == 'D') { |
| 47 | + ny -= d[0]; |
| 48 | + nx -= d[1]; |
| 49 | + if (visited[ny][nx] <= curr.cnt+1) break; |
| 50 | + q.add(new Point(ny, nx, curr.cnt+1)); |
| 51 | + visited[ny][nx] = curr.cnt+1; |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + } |
| 58 | + |
| 59 | + class Point { |
| 60 | + int y, x, cnt; |
| 61 | + public Point(int y, int x, int cnt) { |
| 62 | + this.y = y; |
| 63 | + this.x = x; |
| 64 | + this.cnt = cnt; |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | +``` |
0 commit comments