yukicoder No.367 - ナイトの転身

解法

状態を(場所, コマの種類)として幅優先探索です.

ソースコード

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

struct State {
    int row, col, piece, cost;
};

const int kMAX_H = 510;
const int kMAX_W = 510;

const int kKNIGHT = 0;
const int kMINI_BISHOP = 1;

string S[kMAX_H];

int H, W;
int cost[2][kMAX_H][kMAX_W];

int n_dr[8] = { 1,  1, -1, -1,  2,  2, -2, -2},
    n_dc[8] = { 2, -2,  2, -2,  1, -1,  1, -1};
int b_dr[4] = { 1,  1, -1, -1},
    b_dc[4] = { 1, -1,  1, -1};

void Solve() {
    queue<State> que;
    int sr, sc, gr, gc;
    for (int r = 0; r < H; r++) {
        for (int c = 0; c < W; c++) {
            if (S[r][c] == 'S') {
                sr = r; sc = c;
            } else if (S[r][c] == 'G') {
                gr = r; gc = c;
            }
        }
    }

    memset(cost, -1, sizeof(cost));
    que.push((State){sr, sc, kKNIGHT, 0});
    cost[kKNIGHT][sr][sc] = 0;
    while (!que.empty()) {
        State s = que.front(); que.pop();
        if (s.row == gr && s.col == gc) {
            cout << s.cost << endl;
            return;
        }

        if (s.piece == kKNIGHT) {
            for (int i = 0; i < 8; i++) {
                int nr = s.row + n_dr[i], nc = s.col + n_dc[i];
                if (0 <= nr && nr < H && 0 <= nc && nc < W) {
                    int npiece = S[nr][nc] == 'R' ? kMINI_BISHOP : kKNIGHT;
                    if (cost[npiece][nr][nc] >= 0) continue;

                    que.push((State){nr, nc, npiece, s.cost + 1});
                    cost[npiece][nr][nc] = s.cost + 1;
                }
            }
        } else {
            for (int i = 0; i < 4; i++) {
                int nr = s.row + b_dr[i], nc = s.col + b_dc[i];
                if (0 <= nr && nr < H && 0 <= nc && nc < W) {
                    int npiece = S[nr][nc] == 'R' ? kKNIGHT : kMINI_BISHOP;
                    if (cost[npiece][nr][nc] >= 0) continue;

                    que.push((State){nr, nc, npiece, s.cost + 1});
                    cost[npiece][nr][nc] = s.cost + 1;
                }
            }
        }
    }
    cout << -1 << endl;
}

int main() {
    cin >> H >> W;

    for (int i = 0; i < H; i++) {
        cin >> S[i];
    }

    Solve();

    return 0;
}

感想

典型ですね!