zoukankan      html  css  js  c++  java
  • POJ 2243 Knight Moves

    bfs,使用C++的queue,300ms。

    # include <cstdio>
    # include <cstring>
    # include <queue>
    
    using namespace std;
    
    const int dx[] = {1,1,-1,-1,2,2,-2,-2};
    const int dy[] = {2,-2,2,-2,1,-1,1,-1};
    
    struct Pos{int x, y, d;};
    
    char s[5], g[5];
    int sx, sy, gx, gy;
    
    int bfs(void)
    {
        queue <Pos> Q;
        Pos cur, nst;
        char vis[9][9];
    
        memset(vis, 0, sizeof(vis));
    
        vis[sx][sy] = 1;
        cur.x = sx, cur.y = sy, cur.d = 0;
        Q.push(cur);
        while (!Q.empty())
        {
            cur = Q.front(); Q.pop();
            if (cur.x==gx && cur.y==gy) return cur.d;
            for (int i = 0; i < 8; ++i)
            {
                nst.x = cur.x + dx[i];
                nst.y = cur.y + dy[i];
                if (1<=nst.x&&nst.x<=8 && 1<=nst.y&&nst.y<=8 && !vis[nst.x][nst.y])
                {
                    if (nst.x==gx && nst.y==gy) return cur.d+1;
                    nst.d = cur.d + 1;
                    vis[nst.x][nst.y] = 1;
                    Q.push(nst);
                }
            }
        }
    
    //    return -1;
    }
    
    void solve(void)
    {
        int ans = bfs();
        printf("To get from %s to %s takes %d knight moves.\n", s, g, ans);
    }
    
    int main()
    {
        while (~scanf("%s%s", s, g))
        {
            sx = s[0]-'a'+1;
            sy = s[1]-'1'+1;
            gx = g[0]-'a'+1;
            gy = g[1]-'1'+1;
            solve();
        }
    
        return 0;
    }
  • 相关阅读:
    第六周总结
    第五周总结
    第四周总结
    7-1 抓老鼠啊~亏了还是赚了?
    春季学期第八周作业
    春季学期第七周作业
    春季学期第六周作业
    春季学期第五周作业
    春季学期第四周作业
    春季学期第三周作业
  • 原文地址:https://www.cnblogs.com/JMDWQ/p/2603966.html
Copyright © 2011-2022 走看看