結果
| 問題 | No.124 門松列(3) | 
| コンテスト | |
| ユーザー |  tnakao0123 | 
| 提出日時 | 2016-03-21 00:26:08 | 
| 言語 | C++11(廃止可能性あり) (gcc 13.3.0) | 
| 結果 | 
                                AC
                                 
                             | 
| 実行時間 | 3 ms / 5,000 ms | 
| コード長 | 1,813 bytes | 
| コンパイル時間 | 2,263 ms | 
| コンパイル使用メモリ | 89,548 KB | 
| 実行使用メモリ | 5,248 KB | 
| 最終ジャッジ日時 | 2024-10-01 12:10:24 | 
| 合計ジャッジ時間 | 1,845 ms | 
| ジャッジサーバーID (参考情報) | judge3 / judge1 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 4 | 
| other | AC * 26 | 
ソースコード
/* -*- coding: utf-8 -*-
 *
 * 124.cc: No.124 門松列(3) - yukicoder
 */
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<list>
#include<queue>
#include<deque>
#include<algorithm>
#include<numeric>
#include<utility>
#include<complex>
#include<functional>
 
using namespace std;
/* constant */
const int MAX_W = 100;
const int MAX_H = 100;
const int INF = 1 << 30;
const int dxs[] = {1, 0, -1, 0}, dys[] = {0, -1, 0, 1};
/* typedef */
struct Stat {
  int x, y, a;
  Stat() {}
  Stat(int _x, int _y, int _a): x(_x), y(_y), a(_a) {}
};
/* global variables */
int flds[MAX_H][MAX_W], dists[MAX_H][MAX_W][10];
/* subroutines */
/* main */
int main() {
  int w, h;
  cin >> w >> h;
  for (int y = 0; y < h; y++)
    for (int x = 0; x < w; x++) {
      cin >> flds[y][x];
      for (int a = 0; a < 10; a++) dists[y][x][a] = INF;
    }
  queue<Stat> q;
  if (flds[0][0] != flds[0][1])
    q.push(Stat(1, 0, flds[0][0])), dists[0][1][flds[0][0]] = 1;
  if (flds[0][0] != flds[1][0])
    q.push(Stat(0, 1, flds[0][0])), dists[1][0][flds[0][0]] = 1;
  int mind = INF;
  while (! q.empty()) {
    Stat u = q.front(); q.pop();
    int ud = dists[u.y][u.x][u.a];
    if (u.x == w - 1 && u.y == h - 1) {
      mind = ud;
      break;
    }
    int &b = flds[u.y][u.x];
    int vd = ud + 1;
    
    for (int di = 0; di < 4; di++) {
      int vx = u.x + dxs[di], vy = u.y + dys[di];
      if (vx >= 0 && vx < w && vy >= 0 && vy < h) {
	int &c = flds[vy][vx];
	if (c != u.a && ((u.a < b && b > c) || (u.a > b && b < c)) &&
	    dists[vy][vx][b] > vd) {
	  dists[vy][vx][b] = vd;
	  q.push(Stat(vx, vy, b));
	}
      }
    }
  }
  printf("%d\n", mind >= INF ? -1 : mind);
  return 0;
}
            
            
            
        