Children of the Candy Corn [bfs][dfs]

本文介绍了如何使用BFS寻找迷宫的最短路径,以及利用DFS找出遵循左墙或右墙策略的路径。在输入迷宫后,通过算法计算出各个路径经过的格子数,帮助设计出更复杂的迷宫布局。

The cornfield maze is a popular Halloween treat. Visitors are shown the entrance and must wander through the maze facing zombies, chainsaw-wielding psychopaths, hippies, and other terrors on their quest to find the exit.

One popular maze-walking strategy guarantees that the visitor will eventually find the exit. Simply choose either the right or left wall, and follow it. Of course, there’s no guarantee which strategy (left or right) will be better, and the path taken is seldom the most efficient. (It also doesn’t work on mazes with exits that are not on the edge; those types of mazes are not represented in this problem.)

As the proprieter of a cornfield that is about to be converted into a maze, you’d like to have a computer program that can determine the left and right-hand paths along with the shortest path so that you can figure out which layout has the best chance of confounding visitors.

Input

Input to this problem will begin with a line containing a single integer n indicating the number of mazes. Each maze will consist of one line with a width, w, and height, h (3 <= w, h <= 40), followed by h lines of w characters each that represent the maze layout. Walls are represented by hash marks (‘#’), empty space by periods (‘.’), the start by an ‘S’ and the exit by an ‘E’.

Exactly one ‘S’ and one ‘E’ will be present in the maze, and they will always be located along one of the maze edges and never in a corner. The maze will be fully enclosed by walls (‘#’), with the only openings being the ‘S’ and ‘E’. The ‘S’ and ‘E’ will also be separated by at least one wall (‘#’).

You may assume that the maze exit is always reachable from the start point.

Output

For each maze in the input, output on a single line the number of (not necessarily unique) squares that a person would visit (including the ‘S’ and ‘E’) for (in order) the left, right, and shortest paths, separated by a single space each. Movement from one square to another is only allowed in the horizontal or vertical direction; movement along the diagonals is not allowed.

Sample Input
2
8 8
########
#......#
#.####.#
#.####.#
#.####.#
#.####.#
#...#..#
#S#E####
9 5
#########
#.#.#.#.#
S.......E
#.#.#.#.#
#########
Sample Output
37 5 5
17 17 9

题解

迷宫算法有个贪心算法就是右墙优先算法,计算机导论老师讲机器人走迷宫时讲过。右边通往右转否则前面通前走否则左边同左转否则后转,走一遍能走出迷宫,该算法对我们ACM没有什么利用价值。对于这个题知道按它走一遍即可。

用bfs找最短路。dfs找left or right优先路径。
巧用模运算,以动态对应不同状态下的上下左右,如此可以省略相当一部分代码。

//Accepted 604kB 0ms
#include<stdio.h>
#include<string.h>
#include<queue>
#define MAX_N 42
using namespace std;
char map[MAX_N][MAX_N];
int best[MAX_N][MAX_N];
int W,H,s_x,s_y,e_x,e_y;

//一次是 左 上 右 下
int ox[]={0,1,0,-1};
int oy[]={-1,0,1,0};

int bfs(){
    memset(best,-1,sizeof(best));
    queue<pair<int,int> > que;
    que.push(make_pair(s_x,s_y));
    best[s_x][s_y]=1;

    while(!que.empty()){
        int X=que.front().first,Y=que.front().second;que.pop();
        int step=best[X][Y];
        if(X==e_x&&Y==e_y) return step;
        for(int i=0;i<4;i++){
            int x=X+ox[i];
            int y=Y+oy[i];
            if(0<=x&&x<H&&0<=y&&y<W&&map[x][y]=='.'&&best[x][y]==-1){
                best[x][y]=step+1;
                que.push(make_pair(x,y));
            }
        }
    }
    return -1;
}

int dfs1(int X,int Y,int op){
    if(X==e_x&&Y==e_y) return 1;
    for(int i=0;i<4;i++){
        int x=X+ox[(i+op)%4];
        int y=Y+oy[(i+op)%4];
        if(0<=x&&x<H&&0<=y&&y<W&&map[x][y]=='.')
            return dfs1(x,y,(i+op+3)%4)+1;
    }
}
//一次是 右 上 左 下
int Ox[]={0,1,0,-1};
int Oy[]={1,0,-1,0};
int dfs2(int X,int Y,int op){
    if(X==e_x&&Y==e_y) return 1;
    for(int i=0;i<4;i++){
        int x=X+Ox[(i+op)%4];
        int y=Y+Oy[(i+op)%4];
        if(0<=x&&x<H&&0<=y&&y<W&&map[x][y]=='.')
            return dfs2(x,y,(i+op+3)%4)+1;
    }
}
int sove_b(){

}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--){
        scanf("%d%d",&W,&H);
        for(int i=0;i<H;i++)
            scanf("%s",map[i]);
        for(int k=0;k<H;k++)
            for(int j=0;j<W;j++)
                if(map[k][j]=='S') s_x=k,s_y=j;
                else if(map[k][j]=='E'){
                    map[k][j]='.';
                    e_x=k,e_y=j;
                }
        int a=dfs1(s_x,s_y,0);
        int b=dfs2(s_x,s_y,0);
        int ans=bfs();
        printf("%d %d %d\n",b,a,ans);
    }
    return 0;
}
### BFSDFS 算法的区别及使用场景 BFS(广度优先搜索)和 DFS(深度优先搜索)是两种常见的图遍历算法,它们在思想、实现方式以及适用场景上存在显著差异。 #### 1. **基本思想** - **BFS** 是一种逐层扩展的搜索方式,从起始节点出发,优先访问距离当前节点最近的节点。这种特性使得 BFS 具有最短路径性质,适用于寻找无权图中的最短路径[^2]。 - **DFS** 是一种沿着路径深入的搜索方式,从起始节点出发,尽可能深地探索每个分支,直到无法继续前进时才回溯。这种特性使得 DFS 更适合探索所有可能的路径。 #### 2. **数据结构** - **BFS** 使用队列(Queue)来管理待访问的节点,确保先访问的节点的邻居节点也会优先被访问。 - **DFS** 使用栈(Stack)或递归实现,递归方式更为常见,但容易导致栈溢出。 #### 3. **时间与空间复杂度** - **BFS** 和 **DFS** 的时间复杂度均为 $O(V + E)$,其中 $V$ 是顶点数,$E$ 是边数。 - **BFS** 的空间复杂度通常较高,因为它需要存储每一层的所有节点;而 **DFS** 的空间复杂度取决于递归深度,通常在树的深度较小时表现更好。 #### 4. **适用场景** - **BFS** 更适合以下情况: - 寻找无权图中的最短路径。 - 层次遍历问题,例如按层打印二叉树。 - 需要优先访问距离较近的节点的问题,例如社交网络中查找最近的朋友。 - **DFS** 更适合以下情况: - 探索所有可能的路径,例如迷宫问题。 - 需要回溯的场景,例如图的连通性判断。 - 深度优先的特性使得它在某些问题中更容易实现,例如拓扑排序、判断图中是否存在环。 #### 5. **示例代码** 以下是 **BFS** 和 **DFS** 的简单实现示例: **BFS 实现** ```python from collections import deque def bfs(graph, start): visited = set() queue = deque([start]) visited.add(start) while queue: node = queue.popleft() print(node) for neighbor in graph[node]: if neighbor not in visited: visited.add(neighbor) queue.append(neighbor) ``` **DFS 实现** ```python def dfs(graph, start, visited=None): if visited is None: visited = set() visited.add(start) print(start) for neighbor in graph[start]: if neighbor not in visited: dfs(graph, neighbor, visited) ``` #### 6. **总结** - **BFS** 更适合寻找最短路径或层次遍历问题,而 **DFS** 更适合探索所有可能路径或需要回溯的场景。 - **BFS** 使用队列实现,**DFS** 使用栈或递归实现。 - 在实际应用中,选择哪种算法取决于具体问题的需求和数据结构的特性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值