poj 3083 Children of the Candy Corn 搜索

本文探讨了使用BFS和DFS算法解决迷宫寻路问题,包括最短路径、左优先最短路径及右优先最短路径的求解方法。通过实例分析,展示了算法在路径搜索领域的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:有一迷宫,求从入口到出口的最短路、左优先最短路、右优先最短路。
算法:bfs+dfs

View Code
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
const int maxn = 50;
bool vis[maxn][maxn];
char map[maxn][maxn];

int ldir[4][2] = { {-1,0},{0,1},{1,0},{0,-1} };
int rdir[4][2] = { {-1,0},{0,-1},{1,0},{0,1} };
int n , m;
int ex , ey;

struct Node{
    int x , y , step;
}S;

bool inMap(int x , int y) {
    return x>=0 && x<n && y>=0 && y<m;
}

int bfs() {
    queue<Node> Q;
    Node tmp;
    memset(vis,0,sizeof(vis));
    Q.push(S);
    vis[S.x][S.y] = true;
    while(!Q.empty()) {
        tmp = Q.front(); Q.pop();
        if(map[tmp.x][tmp.y] == 'E') return tmp.step;
        for(int i=0;i<4;i++) {
            int x = tmp.x + ldir[i][0];
            int y = tmp.y + ldir[i][1];
            if(inMap(x , y)) {
                if(map[x][y] != '#' && !vis[x][y]) {
                    Node _node;
                    _node.x = x;
                    _node.y = y;
                    _node.step = tmp.step + 1;
                    vis[x][y] = true;
                    Q.push(_node);
                }
            }
        }
    }
    return 0;
}

int dfs(int r, int c, int d, int dir[][2]) {
    int _row , _col , _d , _step;
    if(map[r][c] == 'E') return 1;
    for(int i=0;i<4;i++) {
        _d = (d + i + 3) % 4;
        _row = r + dir[_d][0];
        _col = c + dir[_d][1];
        if(inMap(_row , _col) && map[_row][_col] != '#') break;
    }
    _step = dfs(_row , _col , _d%4 , dir) + 1;
    return _step;
}

int Init(int &ld , int &rd) {
    if(S.x == 0) ld = rd = 1;
    else if(S.x == n-1) ld = rd = 3;
    else if(S.y == m-1) ld = 0 , rd = 1;
    else if(S.y == 0) ld = 2 , rd = 3;
}

int main() {
    int T;
    scanf("%d",&T);
    while(T--) {
        scanf("%d%d",&m,&n);
        for(int i=0;i<n;i++) {
            scanf("%s",map[i]);
            for(int j=0;j<m;j++) {
                if(map[i][j] == 'S') {
                    S.x = i;
                    S.y = j;
                    S.step = 1;
                }
                if(map[i][j] == 'E') {
                    ex = i;
                    ey = j;
                }
            }
        }
        int ld ,rd;
        Init(ld , rd);
        int ans1 = dfs(S.x , S.y , ld , ldir);
        int ans2 = dfs(S.x , S.y , rd , rdir);
        int ans3 = bfs();
        printf("%d %d %d\n",ans1,ans2,ans3);
    }
    return 0;
}

转载于:https://www.cnblogs.com/lenohoo/archive/2012/07/04/2575559.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值