結果

問題 No.367 ナイトの転身
ユーザー ldsybldsyb
提出日時 2016-04-30 14:04:04
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 27 ms / 2,000 ms
コード長 1,570 bytes
コンパイル時間 826 ms
コンパイル使用メモリ 77,464 KB
実行使用メモリ 6,944 KB
最終ジャッジ日時 2024-04-19 07:43:18
合計ジャッジ時間 1,732 ms
ジャッジサーバーID
(参考情報)
judge3 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <iostream>
#include <queue>
using namespace std;

#define INF 100000000

int h,w,sx,sy,gx,gy,dx4[] = {1,1,-1,-1},dy4[] = {1,-1,-1,1},dx8[] = {2,2,1,1,-1,-1,-2,-2},dy8[] = {1,-1,2,-2,2,-2,1,-1},d[500][500][2];
char board[500][500];

int bfs(){
	queue<pair<int,pair<int,int>>> q;
	q.push(make_pair(1,pair<int,int>(sx,sy)));
	d[sx][sy][1] = 0;
	while(!q.empty()){
		int mode = q.front().first;
		pair<int,int> p = q.front().second;
		q.pop();
		if(p.first == gx && p.second == gy) break;
		if(mode){
			for(int i = 0;i < 8;i++){
				int nx = p.first + dx8[i],ny = p.second + dy8[i],nm = mode ^ (board[nx][ny] == 'R');
				if(nx >= 0 && nx < h && ny >= 0 && ny < w && d[nx][ny][nm] == INF){
					q.push(make_pair(nm,pair<int,int>(nx,ny)));
					d[nx][ny][nm] = d[p.first][p.second][mode] + 1;
				}
			}
		}else{
			for(int i = 0;i < 4;i++){
				int nx = p.first + dx4[i],ny = p.second + dy4[i],nm = mode ^ (board[nx][ny] == 'R');
				if(nx >= 0 && nx < h && ny >= 0 && ny < w && d[nx][ny][nm] == INF){
					q.push(make_pair(nm,pair<int,int>(nx,ny)));
					d[nx][ny][nm] = d[p.first][p.second][mode] + 1;
				}
			}
		}
	}
	return min(d[gx][gy][0],d[gx][gy][1]);
}

int main(){
	cin >> h >> w;
	for(int i = 0;i < h;i++){
		string s;
		cin >> s;
		for(int j = 0;j < w;j++){
			board[i][j] = s[j];
			if(board[i][j] == 'S'){
				sx = i;
				sy = j;
			}else if(board[i][j] == 'G'){
				gx = i;
				gy = j;
			}
		}
	}
	for(int i = 0;i < h;i++) for(int j = 0;j < w;j++) d[i][j][0] = d[i][j][1] = INF;
	int ans = bfs();
	if(ans == INF) ans = -1;
	cout << ans << endl;
}
0