hdu1372 Knight Moves 基础搜索(复习)

http://acm.hdu.edu.cn/showproblem.php?pid=1372


BFS

#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string.h>
#include <vector>
#include <queue>
#include <set>

#define MAXN 100000+5
#define MAX 200000

using namespace std;

struct Point{
    int x,y;
    int step;
    bool operator==(const Point p) const{
        if(x==p.x&&y==p.y) return true;
        return false;
    }
};
int d[8][2]={{1,2},{1,-2},{2,1},{2,-1},{-1,2},{-1,-2},{-2,1},{-2,-1}};
Point st,ed;
bool vis[10][10];

bool legal(Point p){
    if(!vis[p.x][p.y]&&p.x>0&&p.x<9&&p.y>0&&p.y<9)
        return true;
    return false;
}
int bfs(){
    queue<Point>q;
    q.push(st);
    while(!q.empty()){
        Point temp,cur;
        cur=q.front();
        q.pop();
        if(cur==ed)  return cur.step;
        for(int i=0;i<8;i++){
            temp.x=cur.x+d[i][0];
            temp.y=cur.y+d[i][1];
            if(legal(temp)){
            temp.step=cur.step+1;
            q.push(temp);
            }//if
        }//for
    }//while
}
int main(){
    char s1[4],s2[4];
    while(scanf("%s %s",s1,s2)!=EOF){
           // printf("%s%s\n",s1,s2);
           memset(vis,0,sizeof(vis));
        st.x=s1[0]-'a'+1;
        st.y=s1[1]-'0';
        st.step=0;
        ed.x=s2[0]-'a'+1;
        ed.y=s2[1]-'0';
        int ans=bfs();
        printf("To get from %s to %s takes %d knight moves.\n",s1,s2,ans);
    }
    return 0;
}


DFS


#include <stdio.h>
#include <string.h>

int knight[8][8];

int x[8]={1,1,2,2,-1,-1,-2,-2};
int y[8]={2,-2,1,-1,2,-2,1,-1};//8个方向
void dfs(int si,int sj,int moves)
{
    if(si < 0 || sj < 0 || si >7 || sj >7 || moves >= knight[si][sj])
        return;
    knight[si][sj] = moves;
    int i;
    for(i = 0; i < 8; i++)
        dfs(si + x[i],sj + y[i],moves + 1);

}

int main()
{
    char a[5],b[5];
    while(scanf("%s%s",a,b) != EOF)
    {
        memset(knight,10,sizeof(knight));
        dfs(a[0] - 'a',a[1] - '1',0);
        printf("To get from %s to %s takes %d knight moves.\n",a,b,knight[b[0] - 'a'][b[1] - '1']);
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值