zoukankan      html  css  js  c++  java
  • UVA-439, Knight Moves(深度优先搜索)

    #include<iostream>
    #include<queue>
    #include<cstring>
    #include<string>
    #include<cstdio>
    using namespace std;
    struct Point
    {
        int x_, y_;
        int route;
    };
    int dic[8][2] = {-1,2 ,1,2 ,2,1 ,2,-1 ,1,-2 ,-1,-2 ,-2,-1 ,-2,1};
    int vis[10][10];        /*判断是否访问过*/
    string fir, sec;
    int ans;        /*记录最短路*/
    int x1, y1, x2, y2;
    void dfs()
    {
        if(x1 == x2 && y1 == y2)
        {
            ans = 0;
            return ;
        }
    
        Point p;
        p.x_ = x1;
        p.y_ = y1;
        vis[x1][y1] = 1;
        p.route = 0;
        queue<Point> rr;
        rr.push(p);
        while(!rr.empty())
        {
    //        if(x1 == x2 && y1 == y2)
    //            break;
            Point q;
            for(int i = 0; i < 8; i++)
            {
                q.x_ = rr.front().x_ + dic[i][0];
                q.y_ = rr.front().y_ + dic[i][1];
                q.route = rr.front().route + 1;
                if(vis[q.x_][q.y_] == 1 || q.x_ < 0 || q.y_ < 0 || q.x_ > 7 || q.y_ > 7)
                    continue;
                else
                {
                    vis[q.x_][q.y_] = 1;
                    rr.push(q);
                    if(q.x_ == x2 && q.y_ == y2)
                    {
                        ans = q.route;
                        break;                          /*找到了*/
                    }
                }
    
    
    
    
            }
    
            if(q.x_ == x2 && q.y_ == y2)
                break;
            rr.pop();
    
        }
    }
    int main()
    {
        while(cin >> fir >> sec)
        {
            memset(vis, 0, sizeof(vis));
            x1 = (int)fir[0] - 'a';
            y1 = (int)fir[1] - '0' - 1;
            x2 = (int)sec[0] - 'a';
            y2 = (int)sec[1] - '0' - 1;
            dfs();
            cout << "To get from " << fir << " to " << sec << " takes " << ans << " knight moves." << endl;
    
        }
    }
    
    
  • 相关阅读:
    hive_case
    hive_group
    linux-搭建ngnix
    Nfs服务器搭建
    几种常见的启动脚本
    linux 修改本机的端口映射
    oracle-sql计算
    linux 磁盘大小查看
    postMan测试接口的几种方式
    oracle迁移到12c的时列转行 wm_concat 报错解决
  • 原文地址:https://www.cnblogs.com/KeepZ/p/11143798.html
Copyright © 2011-2022 走看看