HDU 2216 简单bfs

简单bfs,只是状态稍微多了两个,四维的bfs,在扩展规则上加了一定的约束。
#include 
#include 
#include 
#include 
#include 
using namespace std;

int dx0[] = {1,-1,0,0} , dx1[] = {-1,1,0,0};
int dy0[] = {0,0,1,-1} , dy1[] = {0,0,-1,1};
int n,m;
char graph[25][25];
bool vis[25][25][25][25];
int ax,ay,bx,by;

struct node{
    int x1,y1,x2,y2;
    int step;
};

bool judge(int x1,int y1,int x2,int y2){
    if(x1==x2 && y1==y2) return true;
    if(abs(x1-x2)==1 && y1==y2) return true;
    if(x1==x2 && abs(y1-y2)==1) return true;
    return false;
}

bool judge1(int x,int y){
    if(x<0 || y<0 || x>=n || y>=m || graph[x][y]=='X')
        return true; //不能走
    return false;
}

int bfs(){
    queue q;
    node cur,next;
    memset(vis,false,sizeof(vis));
    cur.x1 = ax;
    cur.y1 = ay;
    cur.x2 = bx;
    cur.y2 = by;
    cur.step = 0;
    vis[ax][ay][bx][by] = true;
    q.push(cur);
    while(!q.empty()){
        cur = q.front();
        q.pop();
        if(judge(cur.x1,cur.y1,cur.x2,cur.y2))
            return cur.step;
        for(int i=0;i<4;i++){
            next = cur;
            next.x1 = cur.x1+dx0[i];
            next.y1 = cur.y1+dy0[i];
            next.x2 = cur.x2+dx1[i];
            next.y2 = cur.y2+dy1[i];
            next.step = cur.step+1;
            if(judge1(next.x1,next.y1))
                continue;
            if(judge1(next.x2,next.y2)){
                next.x2 = cur.x2;
                next.y2 = cur.y2; //若当前位置不能走,则停留在原地
            }
            if(vis[next.x1][next.y1][next.x2][next.y2])
                continue;
            vis[next.x1][next.y1][next.x2][next.y2] = true;
            q.push(next);
        }
    }
    return -1;
}

int main(){
    while(scanf("%d%d",&n,&m)!=EOF){
        for(int i=0;i

你可能感兴趣的:(bfs)