結果
| 問題 | No.124 門松列(3) |
| コンテスト | |
| ユーザー |
ぴろず
|
| 提出日時 | 2015-01-11 23:43:38 |
| 言語 | Java (openjdk 23) |
| 結果 |
AC
|
| 実行時間 | 331 ms / 5,000 ms |
| コード長 | 2,398 bytes |
| コンパイル時間 | 2,050 ms |
| コンパイル使用メモリ | 78,404 KB |
| 実行使用メモリ | 67,928 KB |
| 最終ジャッジ日時 | 2024-06-13 04:15:51 |
| 合計ジャッジ時間 | 8,952 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | AC * 26 |
ソースコード
package no124;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static int[] di = {1,0,-1,0};
static int[] dj = {0,1,0,-1};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int w = sc.nextInt();
int h = sc.nextInt();
int[][] map = new int[h][w];
for(int i=0;i<h;i++) {
for(int j=0;j<w;j++) {
map[i][j] = sc.nextInt();
}
}
Graph g = new Graph(w*h*10);
for(int i=0;i<h;i++) {
for(int j=0;j<w;j++) {
for(int bef=0;bef<=9;bef++) {
for(int dir=0;dir<4;dir++) {
int ni = i + di[dir];
int nj = j + dj[dir];
if (ni < 0 || ni >= h || nj < 0 || nj >= w) {
continue;
}
if (isKasomatsuSequence(bef, map[i][j], map[ni][nj])) {
g.addEdge(i + j * h + bef * h * w, ni + nj * h + map[i][j] * h * w, 1);
}
}
}
}
}
int[] dist = g.minDistQueue(0);
int ans = Graph.INF;
for(int i=0;i<=9;i++) {
ans = Math.min(ans, dist[h-1 + (w-1) * h + i * h * w]);
}
if (ans == Graph.INF) {
System.out.println(-1);
}else{
System.out.println(ans);
}
}
public static boolean isKasomatsuSequence(int a,int b,int c) {
if (a == 0) {
return true;
}
if (a == b || a == c || b == c) {
return false;
}
return b < a && b < c || b > a && b > c;
}
}
class Graph {
public static final int INF = 1<<29;
int n;
ArrayList<Edge>[] graph;
@SuppressWarnings("unchecked")
public Graph(int n) {
this.n = n;
this.graph = new ArrayList[n];
for(int i=0;i<n;i++) {
graph[i] = new ArrayList<Edge>();
}
}
public void addBidirectionalEdge(int from,int to,int cost) {
addEdge(from,to,cost);
addEdge(to,from,cost);
}
public void addEdge(int from,int to,int cost) {
graph[from].add(new Edge(to, cost));
}
//O(E) all cost is 0 or 1
public int[] minDistQueue(int s) {
int[] d = new int[n];
Arrays.fill(d, INF);
ArrayDeque<Integer> q = new ArrayDeque<Integer>();
q.add(s);
d[s] = 0;
while(!q.isEmpty()) {
int v = q.pollFirst();
for(Edge e:graph[v]) {
int u = e.to;
if (d[v] + e.cost < d[u]) {
d[u] = d[v] + e.cost;
if (e.cost == 0) {
q.addFirst(u);
}else{
q.addLast(u);
}
}
}
}
return d;
}
class Edge {
int to;
int cost;
public Edge(int to,int cost) {
this.to = to;
this.cost = cost;
}
}
}
ぴろず