【POJ】3083- A Children of the Candy Corn DFS、BFS、迷宫靠墙走

9 篇文章 0 订阅

http://poj.org/problem?id=3083
从S到E,分别求靠左边,右边和最短距离到达出口所需步数。

dfs求靠左走的步数,方向数组按照左(0)上(1)右(2)下(3)。
注意:①当前方向的左方向 d=(d+3)%4
比如当前是右(2),此时的左方向是上(1)。
②求起点到终点 的靠右走,即从终点向起点的靠左走。

然后BFS求最短路.

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;

const int maxn=50;
int T,n,m;
int sx,sy,ex,ey;
char G[maxn][maxn];
bool vis[maxn][maxn];
int cnt;
bool flag;
int dir[4][2]={0,-1,-1,0,0,1,1,0};

struct Node{
    int x,y;
    int dis;
};

void dfs(int x,int y,int tx,int ty,int d){
    if (x==tx&&y==ty){
        flag=true;
        cout << cnt << " ";
        return;
    }
    d=(d+3)%4;  //重点,当前方向的左方向 

    for (int i=d;i<d+4;i++){
        int xx=x+dir[i%4][0];
        int yy=y+dir[i%4][1];
        if (xx>=0&&xx<n&&yy>=0&&yy<m&&G[xx][yy]!='#'){
            cnt++;
            dfs(xx,yy,tx,ty,i);
            if (flag){
                return;
            }
        }
    }
}

void bfs(){
    queue <Node> q;
    Node now;
    now.x=sx;
    now.y=sy;
    now.dis=1;
    q.push(now);
    while (!q.empty()){
        now=q.front();
        if (now.x==ex&&now.y==ey){
            cout << now.dis << endl;
            return;
        }
        q.pop();
        for (int i=0;i<4;i++){
            Node temp;
            temp.x=now.x+dir[i][0];
            temp.y=now.y+dir[i][1];
            temp.dis=now.dis+1;
            if (temp.x>=0&&temp.x<n&&temp.y>=0&&temp.y<m&&!vis[temp.x][temp.y]&&G[temp.x][temp.y]!='#'){
                vis[temp.x][temp.y]=true;
                q.push(temp);
            }
        }
    }
}
int main(){

    cin >> T;
    while (T--){
        cin >> m >> n;
        for (int i=0;i<n;i++){
            for (int j=0;j<m;j++){
                cin >> G[i][j];
                if (G[i][j]=='S'){
                    sx=i;
                    sy=j;
                }
                if (G[i][j]=='E'){
                    ex=i;
                    ey=j;
                }
            }
        }

        flag=false;
        cnt=1;
        dfs(sx,sy,ex,ey,0);

        flag=false;
        cnt=1;
        dfs(ex,ey,sx,sy,0);

        flag=false;
        cnt=1;
        memset(vis,false,sizeof(vis));
        bfs();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值