CH2906 武士风度的牛(算竞进阶习题)

水。。。。。

直接bfs。。。

#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
inline int lowbit(int x){ return x & (-x); }
inline int read(){
    int X = 0, w = 0; char ch = 0;
    while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
    while(isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
    return w ? -X : X;
}
inline int gcd(int a, int b){ return a % b ? gcd(b, a % b) : b; }
inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
template<typename T>
inline T max(T x, T y, T z){ return max(max(x, y), z); }
template<typename T>
inline T min(T x, T y, T z){ return min(min(x, y), z); }
template<typename A, typename B, typename C>
inline A fpow(A x, B p, C lyd){
    A ans = 1;
    for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
    return ans;
}
int n, m, f[155][155];
char g[155][155];
pair<int, int> st, ed;
const int dx[] = {-2, -2, 2, 2, -1, -1, 1, 1};
const int dy[] = {-1, 1, -1, 1, -2, 2, -2, 2};

void init(){
    for(int i = 0; i < m; i ++){
        for(int j = 0; j < n; j ++){
            if(g[i][j] == 'K')
                st.first = i, st.second = j, g[i][j] = '.';
            if(g[i][j] == 'H')
                ed.first= i, ed.second = j, g[i][j] = '.';
        }
    }
}

bool inArea(int x, int y){
    return x >= 0 && x < m && y >= 0 && y < n && g[x][y] == '.';
}

int bfs(){
    memset(f, -1, sizeof f);
    queue<pair<int, int>> q;
    f[st.first][st.second] = 0;
    q.push(st);
    while(!q.empty()){
        int x = q.front().first, y = q.front().second; q.pop();
        for(int i = 0; i < 8; i ++){
            int nx = x + dx[i];
            int ny = y + dy[i];
            if(inArea(nx, ny) && f[nx][ny] == -1){
                f[nx][ny] = f[x][y] + 1;
                if(nx == ed.first && ny == ed.second)
                    return f[nx][ny];
                q.push(make_pair(nx, ny));
            }
        }
    }
    return -1;
}

int main(){

    n = read(), m = read();
    for(int i = 0; i < m; i ++) scanf("%s", g[i]);
    init();
    printf("%d\n", bfs());
    return 0;
}
posted @ 2019-03-16 14:38  清楚少女ひなこ  阅读(269)  评论(0编辑  收藏  举报