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

    这道题实到bfs的题目,很简单,不过搜索的方向变成8个而已,对于不会下象棋的会有点晕。

    #include <iostream>
    #include <stdio.h>
    #include <string.h>
    #include <queue>
    using namespace std;
    int c[9][9];
    int dir[8][2] = {{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2}};
    typedef struct
    {
        int x,y,count;
    }node;
    node start,finish;
    int bfs()
    {
        memset(c,0,sizeof(c));
        node pre,cur;
        start.count = 0;
        queue<node> q;
        q.push(start);
        c[start.x][start.y] = 1;
        while(!q.empty())
        {
            pre = q.front();
            q.pop();
            if(pre.x == finish.x&&pre.y == finish.y)
            return pre.count;
            for(int i = 0; i < 8; i++)
            {
                cur.x = pre.x + dir[i][0];
                cur.y = pre.y + dir[i][1];
                if(cur.x<1||cur.x>8||cur.y<1||cur.y>8)continue;
                if(c[cur.x][cur.y]==1)continue;
                c[cur.x][cur.y] = 1;
                cur.count = pre.count + 1;
                q.push(cur);
            }
        }
        return -1;
    }
    int main()
    {
        char row,end;
        int col,ed;
        int min;
        while(scanf("%c",&row)!=EOF)
        {
            scanf("%d",&col);
            getchar();
            scanf("%c%d",&end,&ed);
            getchar();
            start.x = row-'a'+1;
            start.y = col;
            finish.x = end-'a'+1;
            finish.y = ed;
            if(start.x==finish.x&&start.y==finish.y)
            min = 0;
            else  min = bfs();
            printf("To get from %c%d to %c%d takes %d knight moves.
    ",row,col,end,ed,min);
        }
        return 0;
    }
    View Code
  • 相关阅读:
    lvs+keepalived+nginx
    linux配置静态ip
    nginx+keepalived
    nginx反向代理+负载均衡
    win10 安装虚拟机问题
    zlib-1.2.8用VS2010编译生成动态静态库
    mysql 创建库时指定编码
    mysql 升级遇到的问题 (本次由5.1.1X到5.6.28)
    android的SDK包下载
    node-webkit 使用笔记
  • 原文地址:https://www.cnblogs.com/acm-jing/p/4332621.html
Copyright © 2011-2022 走看看