結果
問題 | No.367 ナイトの転身 |
ユーザー |
|
提出日時 | 2016-04-29 23:42:55 |
言語 | Java (openjdk 23) |
結果 |
AC
|
実行時間 | 459 ms / 2,000 ms |
コード長 | 3,832 bytes |
コンパイル時間 | 3,147 ms |
コンパイル使用メモリ | 79,668 KB |
実行使用メモリ | 63,380 KB |
最終ジャッジ日時 | 2024-10-04 19:25:49 |
合計ジャッジ時間 | 6,627 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 27 |
ソースコード
import java.io.*;import java.util.*;public class Main_yukicoder367 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);Printer pr = new Printer(System.out);int h = sc.nextInt();int w = sc.nextInt();char[][] ban = new char[h][];for (int i = 0; i < h; i++) {ban[i] = sc.next().toCharArray();}int sx = 0;int sy = 0;int gx = 0;int gy = 0;for (int i = 0; i < h; i++) {for (int j = 0; j < w; j++) {if (ban[i][j] == 'S') {sx = j;sy = i;}if (ban[i][j] == 'G') {gx = j;gy = i;}}}int[] dxn = {2, 2, 1, 1, -1, -1, -2, -2};int[] dyn = {1, -1, 2, -2, 2, -2, 1, -1};int[] dxb = {1, 1, -1, -1};int[] dyb = {1, -1, 1, -1};Queue<Integer> qx = new ArrayDeque<>();Queue<Integer> qy = new ArrayDeque<>();Queue<Integer> qs = new ArrayDeque<>();Queue<Integer> qc = new ArrayDeque<>();qx.add(sx);qy.add(sy);qs.add(0);qc.add(0);boolean[][][] used = new boolean[2][h][w];used[0][sy][sx] = true;int res = 0;while (!qx.isEmpty()) {int x = qx.remove();int y = qy.remove();int s = qs.remove();int cnt = qc.remove();if (x == gx && y == gy) {res = cnt;break;}if (s == 0) {for (int i = 0; i < dxn.length; i++) {int nx = x + dxn[i];int ny = y + dyn[i];int ns = s;if (nx < 0 || nx >= w || ny < 0 || ny >= h) {continue;}if (ban[ny][nx] == 'R') {ns = (s + 1) % 2;}if (used[ns][ny][nx]) {continue;}used[ns][ny][nx] = true;qx.add(nx);qy.add(ny);qs.add(ns);qc.add(cnt + 1);}} else {for (int i = 0; i < dxb.length; i++) {int nx = x + dxb[i];int ny = y + dyb[i];int ns = s;if (nx < 0 || nx >= w || ny < 0 || ny >= h) {continue;}if (ban[ny][nx] == 'R') {ns = (ns + 1) % 2;}if (used[ns][ny][nx]) {continue;}used[ns][ny][nx] = true;qx.add(nx);qy.add(ny);qs.add(ns);qc.add(cnt + 1);}}}if (res == 0) {pr.println(-1);} else {pr.println(res);}pr.close();sc.close();}@SuppressWarnings("unused")private static class Scanner {BufferedReader br;Iterator<String> it;Scanner (InputStream in) {br = new BufferedReader(new InputStreamReader(in));}String next() throws RuntimeException {try {if (it == null || !it.hasNext()) {it = Arrays.asList(br.readLine().split(" ")).iterator();}return it.next();} catch (IOException e) {throw new IllegalStateException();}}int nextInt() throws RuntimeException {return Integer.parseInt(next());}long nextLong() throws RuntimeException {return Long.parseLong(next());}float nextFloat() throws RuntimeException {return Float.parseFloat(next());}double nextDouble() throws RuntimeException {return Double.parseDouble(next());}void close() {try {br.close();} catch (IOException e) {// throw new IllegalStateException();}}}private static class Printer extends PrintWriter {Printer(PrintStream out) {super(out);}}}