Knight Moves

Posted liuzz-20180701

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Knight Moves相关的知识,希望对你有一定的参考价值。

题目描述

思路

代码描述

#include <cstdio>
#include <cstring>
#include <queue>

int n, m, ans;
struct Node {
    int x, y, z;
}st, ed, tmp;
std::queue<Node> q;
int mp[305][305];
bool vis[305][305];
int dirx[] = {0, -1, -2, -2, -1, 1, 2,  2,  1};
int diry[] = {0, -2, -1,  1,  2, 2, 1, -1, -2};
bool valid(int x, int y) {
    if (x < 0 || x >= m) return false;
    if (y < 0 || y >= m) return false;
    return true;
}
inline int read() {
    int s = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
    return s * f;   
}
int main() {
    n = read();
    while (n--) {
        m = read();
        st.x = read(), st.y = read(), st.z = 0;
        ed.x = read(), ed.y = read();
        tmp.x = st.x, tmp.y = st.y, tmp.z = st.z;
        while (!q.empty()) q.pop();
        memset(vis, 0, sizeof(vis));
        q.push(tmp);
        vis[tmp.x][tmp.y] = true;
        while (!q.empty()) {
            st = q.front();
            q.pop();
            if (st.x == ed.x && st.y == ed.y) {
                ans = st.z; 
                break;
            }
            for (int i = 1; i <= 8; ++i) {
                tmp.x = st.x + dirx[i];
                tmp.y = st.y + diry[i];
                tmp.z = st.z + 1;
                if (valid(tmp.x, tmp.y) && !vis[tmp.x][tmp.y]) {
                    vis[tmp.x][tmp.y] = 1;
                    q.push(tmp);
                }
            }
        }
        printf("%d
", ans);
    }
    return 0;
}

以上是关于Knight Moves的主要内容,如果未能解决你的问题,请参考以下文章

Knight Moves (双向bfs)

UVa439 Knight Moves(dfs)

poj1915 Knight Moves(BFS)

c++ Knight Moves 超级升级版

HDU 1372 Knight Moves(bfs)

习题6-4 骑士的移动(Knight Moves,UVa 439)