1. 程式人生 > >SDNUOJ 1207(BFS)

SDNUOJ 1207(BFS)

Description
上次的馬踏飛燕是不是沒玩夠?無聊的lg準備編寫一款遊戲,就是加強版的“馬踏飛燕”,在這款遊戲中有個一個2000*2000的座標,把馬放在任意一個座標點,再把燕子放在任意一個座標點,並且燕子不會移動,馬只能按照象棋規則走“日”。若200步之內能“踏”到燕子,則成功。lg不知道該怎麼去寫,現在請你幫助他。
走“日”說明:當馬的座標為(5,5)的時候,馬下一步可以走的座標有8個點,分別為(4,3)(6,3)(3,4)(7,4)(3,6)(7,6)(4,7)(6,7)
Input
第一行兩個整數,馬的起始座標x,y (0<x,y<2000)
第一行兩個整數,燕子的座標 m,n (0<m,n<2000)
Output
若4步之內能“踏”到燕子,則輸出“Y”
若4步之內不能“踏”到燕子,則輸出“N”
Sample Input
5 5
7 4
Sample Output
Y
記得標記已訪問過的點,再回到這個點是沒意義的!(受 sjy 師哥啟發)
該BFS模(mu)板 也是該師哥提供,略加補充

#include <cstdio>
#include <iostream>
#include <queue>
#include <cstring>
#include <cmath>
using namespace std;
///目標資料範圍(無)

///8個方向
int dir[][2] = {2,1,1,2,-1,2,-2,1,-2,-1,-1,-2,1,-2,2,-1};
///圖的界線
const int p = 2005;
const int q = 2005;
///訪問標記(無)
bool vis[p][q];
///圖的賦值(無)

///結構體存下標
struct node
{
    int x, y, step;
}now,nex;

void bfs(int x, int y, int m,int n)
{
    now.x = x;
    now.y = y;
    now.step = 0;
    queue<node> Q;
    Q.push(now);
    ///此點訪問標記
    vis[x][y] = 1;
    ///BFS 廣搜
    while(!Q.empty())
    {
        ///首元素(排頭)提取
        now = Q.front();
        ///用完出隊
        Q.pop();
        ///檢測是否符合所求
        if(now.step <= 200)
        {
            if(now.x == m && now.y == n)
            {
                cout << 'Y' << '\n';
                return ;
            }
        }
        else if(now.step > 200)
        {
            cout << 'N' << '\n';
            return ;
        }
        for(int i = 0; i < 8; i++)
        {
            ///將要搜尋的下一個方向的座標
            int xx = now.x + dir[i][0];
            int yy = now.y + dir[i][1];
            ///越界不搜尋
            if(xx < 1 || xx > 2000 || yy < 1 || yy > 2000)
                continue;
            ///非目標點不搜尋
            if(vis[xx][yy])
                continue;
            ///搜完標記
            vis[xx][yy] = 1;
            nex.step = now.step + 1;
            ///新搜的點加入佇列搜
            nex.x = xx;
            nex.y = yy;
            Q.push(nex);
        }
    }
    return ;
}

int main()
{
    int x, y, m, n;
    while(~scanf("%d%d%d%d", &x, &y, &m, &n))
    {
        bfs(x,y,m,n);
    }
    return 0;
}