結果

問題 No.367 ナイトの転身
ユーザー shora_kujira16shora_kujira16
提出日時 2016-04-29 23:00:35
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 25 ms / 2,000 ms
コード長 2,228 bytes
コンパイル時間 1,739 ms
コンパイル使用メモリ 173,532 KB
実行使用メモリ 7,680 KB
最終ジャッジ日時 2024-10-11 00:17:22
合計ジャッジ時間 2,680 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 27
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define REP(i,n) for(int i = 0; i < (int)(n); ++i)
#define DEBUG(x) cerr << #x << " = " << x << endl
constexpr int INF = (int)1e9;
int D[500][500][2];
char M[500][501];
struct NODE {
  int y, x, s;
  NODE(int y_, int x_, int s_) : y(y_), x(x_), s(s_) {}
};
int Kdy[] = {-1, -2, -2, -1, 1, 2, 2, 1};
int Kdx[] = {2, 1, -1, -2, -2, -1, 1, 2};
int Bdy[] = {-1, -1, 1, 1};
int Bdx[] = {1, -1, -1, 1};
signed main() {
  ios::sync_with_stdio(false);
  int H, W; cin >> H >> W;
  REP(i,H) cin >> M[i];
  queue<NODE> Q;
  REP(i,H) REP(j,W) {
    if(M[i][j] == 'S') {
      Q.emplace(i, j, 0);
      D[i][j][0] = 0;
    }
    else {
      D[i][j][0] = INF;
      D[i][j][1] = INF;
    }
  }
  while(!Q.empty()) {
    NODE cur = Q.front(); Q.pop();
    if(cur.s == 0) {
      REP(i,8) {
        int ny = cur.y + Kdy[i];
        int nx = cur.x + Kdx[i];
        if(0 <= ny && ny < H && 0 <= nx && nx < W) {
          if(M[ny][nx] == 'R') {
            if(D[ny][nx][cur.s ^ 1] > D[cur.y][cur.x][cur.s] + 1) {
              D[ny][nx][cur.s ^ 1] = D[cur.y][cur.x][cur.s] + 1;
              Q.emplace(ny, nx, cur.s ^ 1);
            }
          }
          else {
            if(D[ny][nx][cur.s] > D[cur.y][cur.x][cur.s] + 1) {
              D[ny][nx][cur.s] = D[cur.y][cur.x][cur.s] + 1;
              Q.emplace(ny, nx, cur.s);
            }
          }
        }
      }
    }
    else {
      REP(i,4) {
        int ny = cur.y + Bdy[i];
        int nx = cur.x + Bdx[i];
        if(0 <= ny && ny < H && 0 <= nx && nx < W) {
          if(M[ny][nx] == 'R') {
            if(D[ny][nx][cur.s ^ 1] > D[cur.y][cur.x][cur.s] + 1) {
              D[ny][nx][cur.s ^ 1] = D[cur.y][cur.x][cur.s] + 1;
              Q.emplace(ny, nx, cur.s ^ 1);
            }
          }
          else {
            if(D[ny][nx][cur.s] > D[cur.y][cur.x][cur.s] + 1) {
              D[ny][nx][cur.s] = D[cur.y][cur.x][cur.s] + 1;
              Q.emplace(ny, nx, cur.s);
            }
          }
        }
      }
    }
  }
  REP(i,H) REP(j,W) {
    if(M[i][j] == 'G') {
      int ans = min(D[i][j][0], D[i][j][1]);
      if(ans == INF) cout << -1 << endl;
      else cout << ans << endl;
    }
  }
}
0