AOJ.865 青铜莲花池 (BFS)

AOJ.865 青铜莲花池 (BFS)

题意分析

典型的BFS 没的说

代码总览

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <sstream>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cmath>
#define INF 0x3f3f3f3f
#define nmax 35
#define MEM(x) memset(x,0,sizeof(x))
using namespace std;
int m,n,l1,l2,ans;
bool visit[nmax][nmax],isfind = false;
struct p{
    int x;
    int y;
    int time;
}q[nmax],s,e;
bool legal(int x, int y)
{
    if(x<0 || x>=m || y<0 || y>=n) return false;
    if(visit[x][y] == true) return false;
    return true;
}
void bfs(int x, int y)
{
    p temp,lj; temp.x = x; temp.y = y; temp.time = 0;
    int top = 0,bot = 0;
    q[bot++] = s;
    //queue<p> q;
    //q.push(temp);
    int dx[8]= {l1,l1,-l1,-l1,l2,l2,-l2,-l2};
    int dy[8]= {l2,-l2,l2,-l2,l1,-l1,l1,-l1};
    while(top!=bot){
        temp = q[top++];
        for(int k = 0; k<8;++k){
            lj.x = temp.x+dx[k];
            lj.y = temp.y+dy[k];
            lj.time = temp.time+1;
            if(lj.x == e.x && lj.y == e.y){
                ans = lj.time;
                isfind = true;
                break;
            }
            if(legal(lj.x,lj.y)){
                visit[lj.x][lj.y] = true;
                q[bot++] = lj;
            }

        }
        if(isfind) break;
    }
}
void init()
{
    MEM(visit);
    isfind =false;
}
int main()
{
    //freopen("in.txt","r",stdin);
    while(scanf("%d%d",&m,&n) != EOF){
        scanf("%d %d",&l1,&l2);
        init();
        int t;
        for(int i = 0 ;i<m;++i)
            for(int j = 0; j<n;++j){
                scanf("%d",&t);
                if(t == 3){
                    s.x = i; s.y = j;
                }else if(t == 4){
                    e.x = i; e.y = j;
                }else if(t == 0|| t == 2){
                    visit[i][j] = true;
                }
            }
        bfs(s.x,s.y);
        printf("%d\n",ans);
    }
    return 0;
}
posted @ 2017-04-28 21:14  pengwill  阅读(279)  评论(0编辑  收藏  举报