結果
問題 | No.367 ナイトの転身 |
ユーザー |
|
提出日時 | 2016-04-29 23:37:09 |
言語 | C++11(廃止可能性あり) (gcc 13.3.0) |
結果 |
AC
|
実行時間 | 32 ms / 2,000 ms |
コード長 | 2,053 bytes |
コンパイル時間 | 559 ms |
コンパイル使用メモリ | 65,560 KB |
実行使用メモリ | 6,820 KB |
最終ジャッジ日時 | 2024-10-04 19:18:45 |
合計ジャッジ時間 | 1,449 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 27 |
ソースコード
#include<iostream> #include<queue> #include<cstring> using namespace std; const int BUF = 505; class Data { public: bool type; int r, c; Data(){} Data(bool type, int r, int c): type(type), r(r), c(c){} }; int row, col; int bgnR, bgnC; int endR, endC; bool isRed[BUF][BUF]; void read() { memset(isRed, 0, sizeof(isRed)); cin >> row >> col; for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) { char ch; cin >> ch; isRed[i][j] = ch == 'R'; if (ch == 'S') { bgnR = i; bgnC = j; } if (ch == 'G') { endR = i; endC = j; } } } } void work() { queue<Data> Q; int cost[2][BUF][BUF]; memset(cost, -1, sizeof(cost)); Q.push(Data(0, bgnR, bgnC)); cost[0][bgnR][bgnC] = 0; while (!Q.empty()) { Data curr = Q.front(); Q.pop(); if (curr.r == endR && curr.c == endC) { cout << cost[curr.type][curr.r][curr.c] << endl; return; } // knight の動き static int kdr[] = {-2, -1, 1, 2, 2, 1, -1, -2}; static int kdc[] = { 1, 2, 2, 1, -1, -2, -2, -1}; // mini bishop の動き static int bdr[] = {-1, 1, 1, -1}; static int bdc[] = { 1, 1, -1, -1}; for (int i = 0; i < (curr.type == 0 ? 8 : 4); ++i) { int nr = curr.r + (curr.type == 0 ? kdr[i] : bdr[i]); int nc = curr.c + (curr.type == 0 ? kdc[i] : bdc[i]); if (!(0 <= nr && nr < row && 0 <= nc && nc < col)) continue; bool nType = isRed[nr][nc] ? !curr.type : curr.type; if (cost[nType][nr][nc] == -1) { cost[nType][nr][nc] = cost[curr.type][curr.r][curr.c] + 1; Q.push(Data(nType, nr, nc)); } } } cout << -1 << endl; } int main() { read(); work(); return 0; }