zoukankan      html  css  js  c++  java
  • poj 2243

    BFS

    #include <iostream>
    #include <stdio.h>
    #include <queue>
    #include <vector>
    #include <string.h>
    #include <algorithm>
    using namespace std;
    struct node
    {
        int x,y;
    };
    int dir[8][2]={-2,-1,-2,1,-1,-2,-1,2,1,-2,1,2,2,-1,2,1};
    int move[10][10];
    int ex,ey;
    bool OK(node &b)
    {
        if(b.x<1||b.x>8||b.y<1||b.y>8||move[b.x][b.y])
          return false;
        return true;
    }
    void BFS(int x,int y)
    {
        node a,b;
        queue<node> Q;
        a.x=x;  a.y=y;
        Q.push(a);
        int i;
        while(!Q.empty())
        {
            a=Q.front();Q.pop();
            
            for(i=0;i<8;i++)
            {
                b.x=a.x+dir[i][0];
                b.y=a.y+dir[i][1];
                if(b.x==x&&b.y==y) continue;
                if(OK(b))
                 {
                     move[b.x][b.y]=move[a.x][a.y]+1;
                     Q.push(b);
                 }
                if(b.x==ex&&b.y==ey) return;
            }
        }
    
    }
    int main()
    {
       char op1[5],op2[5];
       while(scanf("%s %s",op1,op2)!=EOF)
       {
           memset(move,0,sizeof(move));
           int x=op1[0]-'a'+1  ,   y=op1[1]-'0';
               ex=op2[0]-'a'+1; 
               ey=op2[1]-'0';
         //  printf("%d %d==
    ",ex,ey);
         
           if(x!=ex||y!=ey)
             BFS(x,y);
        printf("To get from %s to %s takes %d knight moves.
    ",op1,op2,move[ex][ey]);
    
       }
    }
    View Code
  • 相关阅读:
    CSUFT 1002 Robot Navigation
    CSUFT 1003 All Your Base
    Uva 1599 最佳路径
    Uva 10129 单词
    欧拉回路
    Uva 10305 给任务排序
    uva 816 Abbott的复仇
    Uva 1103 古代象形文字
    Uva 10118 免费糖果
    Uva 725 除法
  • 原文地址:https://www.cnblogs.com/2014acm/p/3898960.html
Copyright © 2011-2022 走看看