1015-Knight Moves


1.题号:1015-Knight Moves

2.题意:a-h   1-8,,,前者横坐标,后者纵坐标,要求走“日”字形,问最少几步?

3.解创建结构体,内涵行列和步数,定义好个方向,bfs,每一个方向,越界、访问两次继续,找到截止(用队列来进行存储。先表示出来起点终点的行列坐标,然后广搜即可。

4.感悟:经典bfs,多做练习

5.AC代码:

#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}};///8个方向

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.\n",row,col,end,ed,min);
    }
    return 0;
}
















你可能感兴趣的:(搜索)