hoj 1440 bfs

http://acm.hit.edu.cn/hoj/problem/view?id=1440

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;

struct state {
    int x,y;
    int step;
};
char s[5],e[4];
int visited[10][10];
int dir[8][2] ={1,2,2,1,-1,2,-2,1,1,-2,2,-1,-1,-2,-2,-1};
queue<state>q;

bool check(state s){
    if(s.x>0&& s.y > 0 &&s.x <9&& s.y < 9 &&!visited[s.x][s.y])
       return1;
    return 0;
}
int bfs(state st){
    state now,next;
    st.step = 0;
    q.push(st);
    visited[st.x][st.y] = 1;
    while(!q.empty()){
       now = q.front();
       if(now.x == e[2]&& now.y == e[3])
          return now.step;
       for(int i = 0; i < 8; i++) {
          next.x = now.x + dir[i][0];
          next.y = now.y + dir[i][1];
          next.step = now.step + 1;
          if(check(next)){
              q.push(next);
              visited[next.x][next.y] = 1;
           }
       }
       q.pop();
    }
    return 0;
}
int main(){
    while(gets(s)){
       e[0] =s[0] - 'a' + 1;
       e[1] =s[1] - '0';
       e[2] =s[3] - 'a' + 1;
       e[3] =s[4] - '0';
       statestart;
       start.x =e[0];
       start.y =e[1];
       while(!q.empty()) 
          q.pop();
       memset(visited, 0, sizeof(visited));
       printf("To get from %c%c to %c%c takes %d knightmoves.\n",s[0],s[1],s[3],s[4],bfs(start));
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值