結果
| 問題 |
No.367 ナイトの転身
|
| コンテスト | |
| ユーザー |
uafr_cs
|
| 提出日時 | 2017-11-01 18:44:25 |
| 言語 | Java (openjdk 23) |
| 結果 |
AC
|
| 実行時間 | 795 ms / 2,000 ms |
| コード長 | 2,705 bytes |
| コンパイル時間 | 2,375 ms |
| コンパイル使用メモリ | 79,424 KB |
| 実行使用メモリ | 59,608 KB |
| 最終ジャッジ日時 | 2024-11-22 14:39:06 |
| 合計ジャッジ時間 | 10,937 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 27 |
ソースコード
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
public static long MOD = 1000000007;
public static final int INF = Integer.MAX_VALUE / 2 - 1;
public static boolean in_range(int x, int y, int W, int H){
return 0 <= x && x < W && 0 <= y && y < H;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
final int H = sc.nextInt();
final int W = sc.nextInt();
int sx = -1, sy = -1, gx = -1, gy = -1;
boolean[][] is_red = new boolean[H][W];
for(int i = 0; i < H; i++){
final char[] ins = sc.next().toCharArray();
for(int j = 0; j < W; j++){
if(ins[j] == 'R'){
is_red[i][j] = true;
}else if(ins[j] == 'S'){
sx = j; sy = i;
}else if(ins[j] == 'G'){
gx = j; gy = i;
}
}
}
LinkedList<Integer> queue = new LinkedList<Integer>();
final int KNIGHT = 0, MINB = 1;
int[][][] costs = new int[H][W][2];
for(int i = 0; i < H; i++){
for(int j = 0; j < W; j++){
costs[i][j][0] = INF;
costs[i][j][1] = INF;
}
}
costs[sy][sx][KNIGHT] = 0;
queue.add(sx); queue.add(sy); queue.add(KNIGHT);
while(!queue.isEmpty()){
final int x = queue.poll();
final int y = queue.poll();
final int type = queue.poll();
//System.out.println(x + " " + y + " " + (type == KNIGHT ? "N" : "B"));
if(type == MINB){
for(int dy = -1; dy <= 1; dy++){
for(int dx = -1; dx <= 1; dx++){
if(dx == 0 && dy == 0){ continue; }
if(Math.abs(dx) == 0 || Math.abs(dy) == 0){ continue; }
final int nx = x + dx;
final int ny = y + dy;
if(!in_range(nx, ny, W, H)){ continue; }
final int next_type = is_red[ny][nx] ? 1 - type : type;
if(costs[ny][nx][next_type] <= costs[y][x][type] + 1){ continue; }
costs[ny][nx][next_type] = costs[y][x][type] + 1;
queue.add(nx); queue.add(ny); queue.add(next_type);
}
}
}else{
for(int dy = -2; dy <= 2; dy++){
for(int dx = -2; dx <= 2; dx++){
if(Math.abs(dx) == Math.abs(dy)){ continue; }
if(Math.min(Math.abs(dx), Math.abs(dy)) == 0){ continue; }
final int nx = x + dx;
final int ny = y + dy;
if(!in_range(nx, ny, W, H)){ continue; }
final int next_type = is_red[ny][nx] ? 1 - type : type;
if(costs[ny][nx][next_type] <= costs[y][x][type] + 1){ continue; }
costs[ny][nx][next_type] = costs[y][x][type] + 1;
queue.add(nx); queue.add(ny); queue.add(next_type);
}
}
}
}
final int min_cost = Math.min(costs[gy][gx][KNIGHT], costs[gy][gx][MINB]);
System.out.println(min_cost >= INF ? -1 : min_cost);
}
}
uafr_cs