BFS 搜索 Problem 1015 Knight Moves "馬走日"之最少步數

Problem ID:1015 Knight Moves


簡單題意:給出一個8*8的棋盤,一個起始點,一個目的點,從起始點開始,按照“馬走日”規則行走。求到達目的點的最少步數。


解題思路形成過程:用BFS的方式進行遍歷,每個點可以往8個方向前進。

            如果前進需要滿足2個條件:①:此點在棋盤內;

                             ②:此點在之前沒有遍歷過。

            利用數組儲存地圖以及行走過的點。


感想:注意字符類型的輸入處理。

    注意數組不要超出範圍(debug了好一會兒)。


代碼:

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
int dir[8][2]={{-1,-2},{-2,-1},{-1,2},{-2,1},{1,-2},{2,-1},{1,2},{2,1}};//八個方向
int cmap[8][8];
char a1,b1;
int  a2,b2;
int bfs(int r,int c)
{
    queue<int>q;
    q.push(r);
    q.push(c);
    q.push(0);
    while(!q.empty())
    {
        int nr=q.front();
        q.pop();
        int nc=q.front();
        q.pop();
        int nct=q.front();
        q.pop();
        for(int i=0;i<8;++i){
            int tr=nr+dir[i][0];
            int tc=nc+dir[i][1];
            int tct=nct+1;
            if(tr>=0&&tr<8&&tc>=0&&tc<8){
                if(cmap[tr][tc]==2)     //此條件語句不能單獨列出,必須在if(tr>=0&&tr<8&&tc>=0&&tc<8)內,否則會出錯!
                  return tct;
                if(cmap[tr][tc]==0){
                    q.push(tr);
                    q.push(tc);
                    q.push(tct);
                    cmap[tr][tc]=1;
                }
            }
        }
    }
}
int main()
{
    //freopen("1.txt","r",stdin);
    while(scanf("%c",&a1)!=EOF)
    {
        scanf("%d",&a2);//注意字符類型的輸入處理。
        getchar();
        scanf("%c%d",&b1,&b2);
        getchar();
        memset(cmap,0,sizeof(cmap));
        int r1=a2-1;
        int c1=a1-'a';
        int r2=b2-1;
        int c2=b1-'a';
        cmap[r1][c1]=1;
        cmap[r2][c2]=2;
        if(r1==r2&&c1==c2){
            printf("To get from %c%d to %c%d takes 0 knight moves.\n",a1,a2,b1,b2);
            continue;
        }
        int cnt=bfs(r1,c1);
        printf("To get from %c%d to %c%d takes %d knight moves.\n",a1,a2,b1,b2,cnt);
    }
    return 0;
}


發佈了48 篇原創文章 · 獲贊 4 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章