zoukankan      html  css  js  c++  java
  • poj2243

    BFS

    View Code
    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <cstring>
    #include <queue>
    using namespace std;
    
    #define maxn 10
    
    struct Point
    {
        int x, y;
    }s, t;
    
    int dir[8][2] = {{1, 2}, {1, -2}, {-1, 2}, {-1, -2}, {2, 1}, {-2, 1}, {2, -1}, {-2, -1}};
    
    bool in_bound(Point a)
    {
        return a.x >= 0 && a.y >= 0 && a.x < 8 && a.y < 8;
    }
    
    int bfs()
    {
        if (s.x == t.x && s.y == t.y)
            return 0;
        queue <Point> q;
        bool vis[maxn][maxn];
        int dist[maxn][maxn];
        memset(vis, 0, sizeof(vis));
        q.push(s);
        vis[s.x][s.y] = true;
        dist[s.x][s.y] = 0;
        while (!q.empty())
        {
            Point a = q.front();
            q.pop();
            for (int i = 0; i < 8; i++)
            {
                Point b;
                b.x = a.x + dir[i][0];
                b.y = a.y + dir[i][1];
                if (in_bound(b) && !vis[b.x][b.y])
                {
                    vis[b.x][b.y] = true;
                    dist[b.x][b.y] = dist[a.x][a.y] + 1;
                    q.push(b);
                    if (b.x == t.x && b.y == t.y)
                        return dist[b.x][b.y];
                }
            }
        }
        return -1;
    }
    
    int main()
    {
    //    freopen("t.txt", "r", stdin);
        char st1[10], st2[10];
        while (~scanf("%s", st1))
        {
            s.x = st1[0] - 'a';
            s.y = st1[1] - '1';
            scanf("%s", st2);
            t.x = st2[0] - 'a';
            t.y = st2[1] - '1';
            printf("To get from %s to %s takes %d knight moves.\n", st1, st2, bfs());
        }
        return 0;
    }
  • 相关阅读:
    动态内存Treap
    最大流Dinic
    图的遍历
    Aho_Corasick自动机(AC自动机)
    邻接表
    COJ 3007 Mr.Yang的小助手
    COJ 0601&0602 动态规划(二)及加强
    Codeforces 603A Alternative Thinking
    HDU 2222 Keywords Search
    codeforce--600D
  • 原文地址:https://www.cnblogs.com/rainydays/p/2857663.html
Copyright © 2011-2022 走看看