# Yukicoder No.124 門松列(3)

,

http://yukicoder.me/problems/no/124

## implementation

$O(HW\max A_i)$で解いた。

#include <iostream>
#include <vector>
#include <queue>
#include <cassert>
#define repeat(i,n) for (int i = 0; (i) < (n); ++(i))
using namespace std;
template <typename T, typename X> auto vectors(T a, X x) { return vector<T>(x, a); }
template <typename T, typename X, typename Y, typename... Zs> auto vectors(T a, X x, Y y, Zs... zs) { auto cont = vectors(a, y, zs...); return vector<decltype(cont)>(x, cont); }
const int inf = 1e9+7;
const int dy[] = { -1, 1, 0, 0 };
const int dx[] = { 0, 0, 1, -1 };
struct state_t { int y, x, last, dist; };
bool operator < (state_t const & a, state_t const & b) { return a.dist > b.dist; } // reversed, weak
bool is_kadomatsu_sequence(int a, int b, int c) {
if (a == 0) return true;
return ((a < b and b > c) or (a > b and b < c)) and a != c;
}
int main() {
// input
int w, h; cin >> w >> h;
vector<vector<int> > m = vectors(int(), h, w);
repeat (y,h) repeat (x,w) cin >> m[y][x];
repeat (y,h) repeat (x,w) assert (1 <= m[y][x] and m[y][x] <= 9);
auto is_on_field = [&](int y, int x) { return 0 <= y and y < h and 0 <= x and x < w; };
// dijkstra
// // initialize
vector<vector<vector<int> > > dist = vectors(inf, h, w, 10);
priority_queue<state_t> que; {
state_t a;
a.y = 0;
a.x = 0;
a.last = 0;
a.dist = 0;
que.push(a);
}
// // loop
int ans = -1;
while (not que.empty()) {
state_t a = que.top(); que.pop();
if (a.y == h-1 and a.x == w-1) {
ans = a.dist;
break;
}
repeat (i,4) {
state_t b = a;
b.y += dy[i];
b.x += dx[i];
b.last = m[a.y][a.x];
b.dist += 1;
if (not is_on_field(b.y, b.x)) continue;
if (not is_kadomatsu_sequence(a.last, b.last, m[b.y][b.x])) continue;
if (dist[b.y][b.x][b.last] != inf) continue;
dist[b.y][b.x][b.last] = b.dist;
que.push(b);
}
}
// output
cout << ans << endl;
return 0;
}