結果

問題 No.124 門松列(3)
ユーザー krotonkroton
提出日時 2015-01-10 18:26:45
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 3 ms / 5,000 ms
コード長 1,452 bytes
コンパイル時間 2,277 ms
コンパイル使用メモリ 148,560 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-09-03 22:57:10
合計ジャッジ時間 2,602 ms
ジャッジサーバーID
(参考情報)
judge14 / judge15
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 3 ms
4,380 KB
testcase_01 AC 1 ms
4,384 KB
testcase_02 AC 1 ms
4,380 KB
testcase_03 AC 3 ms
4,380 KB
testcase_04 AC 3 ms
4,376 KB
testcase_05 AC 3 ms
4,380 KB
testcase_06 AC 1 ms
4,380 KB
testcase_07 AC 2 ms
4,380 KB
testcase_08 AC 2 ms
4,376 KB
testcase_09 AC 1 ms
4,380 KB
testcase_10 AC 1 ms
4,376 KB
testcase_11 AC 1 ms
4,376 KB
testcase_12 AC 1 ms
4,376 KB
testcase_13 AC 2 ms
4,376 KB
testcase_14 AC 1 ms
4,380 KB
testcase_15 AC 2 ms
4,376 KB
testcase_16 AC 2 ms
4,380 KB
testcase_17 AC 1 ms
4,384 KB
testcase_18 AC 1 ms
4,376 KB
testcase_19 AC 2 ms
4,380 KB
testcase_20 AC 2 ms
4,376 KB
testcase_21 AC 1 ms
4,380 KB
testcase_22 AC 2 ms
4,376 KB
testcase_23 AC 2 ms
4,380 KB
testcase_24 AC 3 ms
4,384 KB
testcase_25 AC 2 ms
4,380 KB
testcase_26 AC 2 ms
4,376 KB
testcase_27 AC 2 ms
4,380 KB
testcase_28 AC 3 ms
4,376 KB
testcase_29 AC 3 ms
4,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
 
const int INF = 1 << 25;
 
int dy[] = {0, 0, 1, -1};
int dx[] = {1, -1, 0, 0};
 
int W, H, M[111][111];
int dist[111][111][11];
 
struct State { int y, x, pre; };
 
bool is_kadomatu(int a, int b, int c){
	if(a < b && c < b && a != c)
		return true;
	if(a > b && c > b && a != c)
		return true;
	return false;
}
 
int main(){
	cin >> W >> H;
	for(int i=0;i<H;i++)
		for(int j=0;j<W;j++)
			cin >> M[i][j];
 
	for(int i=0;i<H;i++)
		for(int j=0;j<W;j++)
			for(int k=1;k<=9;k++)
				dist[i][j][k] = INF;
 
	queue<State> Q;
 
	// first step
	for(int i=0;i<4;i++){
		int pre = M[0][0];
		int ny = dy[i];
		int nx = dx[i];
 
		if(ny < 0 || nx < 0 || ny >= H || nx >= W)
			continue;
 
		if(M[ny][nx] == pre)
			continue;
 
		dist[ny][nx][pre] = 1;
		Q.push(State{ny, nx, pre});
	}
 
	while(!Q.empty()){
		auto st = Q.front(); Q.pop();
		int y = st.y;
		int x = st.x;
		int pre = st.pre;
		int crr = M[y][x];
		int cost = dist[y][x][pre];
 
		for(int i=0;i<4;i++){
			int ny = y + dy[i];
			int nx = x + dx[i];
			int nc = cost + 1;
 
			if(ny < 0 || nx < 0 || ny >= H || nx >= W)
				continue;
 
			if(!is_kadomatu(pre, crr, M[ny][nx]))
				continue;
 
			if(nc >= dist[ny][nx][crr])
				continue;
 
			dist[ny][nx][crr] = nc;
			Q.push(State{ny, nx, crr});
		}
	}
 
	int res = INF;
	for(int k=1;k<=9;k++)
		res = min(res, dist[H-1][W-1][k]);
 
	if(res >= INF)
		res = -1;
 
	cout << res << endl;
	return 0;
}
0