zoukankan      html  css  js  c++  java
  • POJ1915 Knight Moves

    问题链接:POJ1915 Knight Moves

    题意简述:输入测试用例数量,输入棋盘大小,输入国际象棋棋盘中的两个点,求马从一个点跳到另一个点的最少步数。

    问题分析:典型的BFS问题。在BFS搜索过程中,马跳过的点就不必再跳了,因为这次再跳下去不可能比上次步数少。

    程序中,使用了一个队列来存放中间节点,但是每次用完需要清空。


    AC的C++语言程序如下:

    /* POJ1915 Knight Moves */
    
    #include <cstdio>
    #include <cstring>
    #include <queue>
    
    using namespace std;
    
    #define MAXN 300
    
    #define DIRECTSIZE 8
    
    struct direct {
        int drow;
        int dcol;
    } direct[DIRECTSIZE] =
        {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}};
    
    char grid[MAXN][MAXN];
    
    int n, l;
    int startcol, startrow, endcol, endrow;
    int ans;
    
    struct node {
        int row;
        int col;
        int level;
    };
    
    void bfs()
    {
        queue<node> q;
    
        memset(grid, 0, sizeof(grid));
    
        grid[startrow][startcol] = 1;
    
        ans = 0;
        node start;
        start.row = startrow;
        start.col = startcol;
        start.level = 0;
        q.push(start);
    
        while(!q.empty()) {
            node front = q.front();
            q.pop();
    
            if(front.row == endrow && front.col == endcol) {
                ans = front.level;
                break;
            }
    
            for(int i=0; i<DIRECTSIZE; i++) {
                int nextrow = front.row + direct[i].drow;
                int nextcol = front.col + direct[i].dcol;
    
                if(0 <= nextrow && nextrow < l && 0 <= nextcol && nextcol < l)
                    if(grid[nextrow][nextcol] == 0) {
                        grid[nextrow][nextcol] = 1;
    
                        node v;
                        v.row = nextrow;
                        v.col = nextcol;
                        v.level = front.level + 1;
                        q.push(v);
                    }
            }
        }
    }
    
    int main(void)
    {
        scanf("%d", &n);
        while(n--) {
            scanf("%d%d%d%d%d", &l, &startrow, &startcol, &endrow, &endcol);
    
            bfs();
    
            printf("%d
    ", ans);
        }
    
        return 0;
    }


  • 相关阅读:
    Qt Examples Qt实例汇总
    [转帖] VS集成Qt环境搭建
    GTKmm 学习资料
    Programming with gtkmm 3
    CvMat and cv::Mat
    [LeetCode] Longest Consecutive Sequence 求最长连续序列
    [转帖] CvMat,Mat和IplImage之间的转化和拷贝
    [LeetCode] Sum Root to Leaf Numbers 求根到叶节点数字之和
    [LeetCode] Palindrome Partitioning II 拆分回文串之二
    [LeetCode] Palindrome Partitioning 拆分回文串
  • 原文地址:https://www.cnblogs.com/tigerisland/p/7564454.html
Copyright © 2011-2022 走看看