結果
| 問題 | No.124 門松列(3) |
| コンテスト | |
| ユーザー |
uafr_cs
|
| 提出日時 | 2015-09-16 18:19:58 |
| 言語 | Java (openjdk 23) |
| 結果 |
AC
|
| 実行時間 | 236 ms / 5,000 ms |
| コード長 | 2,151 bytes |
| コンパイル時間 | 2,253 ms |
| コンパイル使用メモリ | 79,568 KB |
| 実行使用メモリ | 47,288 KB |
| 最終ジャッジ日時 | 2024-07-19 06:41:13 |
| 合計ジャッジ時間 | 8,686 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | AC * 26 |
ソースコード
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.Set;
public class Main {
public static final int[][] move_dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public static boolean is_valid(int x, int y, int W, int H){
return x >= 0 && x < W && y >= 0 && y < H;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
final int W = sc.nextInt();
final int H = sc.nextInt();
int[][] heights = new int[H][W];
for(int i = 0; i < H; i++){
for(int j = 0; j < W; j++){
heights[i][j] = sc.nextInt();
}
}
LinkedList<Integer> x_queue = new LinkedList<Integer>();
LinkedList<Integer> y_queue = new LinkedList<Integer>();
LinkedList<Integer> prev_queue = new LinkedList<Integer>();
int[][][] minimum_cost = new int[10][H][W];
for(int i = 0; i < 10; i++){
for(int j = 0; j < H; j++){
for(int k = 0; k < W; k++){
minimum_cost[i][j][k] = Integer.MAX_VALUE;
}
}
}
minimum_cost[0][0][0] = 0;
x_queue.add(0);
y_queue.add(0);
prev_queue.add(0);
while(!x_queue.isEmpty()){
final int x = x_queue.poll();
final int y = y_queue.poll();
final int curr = heights[y][x];
final int prev = prev_queue.poll();
if(curr == prev){
continue;
}else if(x == W - 1 && y == H - 1 && prev > 0){
System.out.println(minimum_cost[prev][y][x]);
return;
}
//System.out.println(x + " " + y + " " + prev + " " + minimum_cost[prev][y][x]);
for(final int[] move : move_dir){
final int nx = x + move[0];
final int ny = y + move[1];
if(!is_valid(nx, ny, W, H)){
continue;
}
final int next = heights[ny][nx];
if(prev == next){
continue;
}
final int next_cost = minimum_cost[prev][y][x] + 1;
if(prev == 0 || prev < curr && curr > next || prev > curr && curr < next){
if(minimum_cost[curr][ny][nx] > next_cost){
minimum_cost[curr][ny][nx] = next_cost;
x_queue.add(nx);
y_queue.add(ny);
prev_queue.add(curr);
}
}
}
}
System.out.println(-1);
}
}
uafr_cs