1. 程式人生 > >POJ 1915_雙向BFS

POJ 1915_雙向BFS

前提

使用雙向BFS前提是:我們要知道起點和終點的位置,並且這個題要使用BFS求解

我們分別從起點和終點開始進行BFS,以起點開始的BFS的將標記陣列記為1,以終點開始的BFA標記陣列為2,那麼當起點的BFS遇到標記為2的點時或者終點為起點的BFS遇到標記為1的點時我們就找到了答案,答案就是兩邊步數的相加......

雙向BFS的基本思路是這樣的.....下面試程式的實現:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <cmath>
#include <vector>
#include <algorithm>

using namespace std;
const int M = 310;
int vis[M][M],step[M][M],len;
const int dx[8] = {-1,-2,-2,-1,1,2,2,1};
const int dy[8] = {-2,-1,1,2,2,1,-1,-2};
struct node{
    int x,y;
    node(){}
    node(int x,int y):x(x),y(y){}
}st,en;

int limit(node a){
    return (a.x >= 0 && a.x < len && a.y >= 0 && a.y < len);
}

int BFS()
{
    if(st.x == en.x && st.y == en.y)return 0;
    queue<node> que[2];
    que[0].push(st);que[1].push(en);
    vis[st.x][st.y] = 1;vis[en.x][en.y] = 2;
    while(!que[0].empty() && !que[1].empty())
    {
        if(!que[0].empty())
        {
            node q = que[0].front();que[0].pop();
            for(int i =0 ;i < 8;i ++)
                if(limit(node(q.x + dx[i],q.y + dy[i])))
                {
                    node now = node(q.x + dx[i],q.y+dy[i]);
                    if(vis[now.x][now.y] == 2)
                        return step[q.x][q.y] + step[now.x][now.y]+1;
                    else if(!vis[now.x][now.y])
                    {
                        vis[now.x][now.y] = 1;
                        step[now.x][now.y] = step[q.x][q.y] +1;
                        que[0].push(now);
                    }
                }
        }
        if(!que[1].empty())
        {
            node q = que[1].front();que[1].empty();
            for(int i = 0;i < 8;i ++)
                if(limit(node(q.x + dx[i],q.y+dy[i])))
                {
                    node now = node(q.x + dx[i],q.y + dy[i]);
                    if(vis[now.x][now.y] == 1)
                        return step[q.x][q.y] + step[now.x][now.y] +1;
                    else if(!vis[now.x][now.y])
                    {
                        vis[now.x][now.y] = 2;
                        step[now.x][now.y] = step[q.x][q.y] +1;
                        que[1].push(now);
                    }
                }
        }
    }
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&len);
        scanf("%d%d%d%d",&st.x,&st.y,&en.x,&en.y);
        memset(vis,0,sizeof(vis));
        memset(step,0,sizeof(step));
        printf("%d\n",BFS());
    }
    return 0;
}