虽说是宽搜模板题,但是用深搜也是可以解决的

代码如下:

#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
int r, c;
char map[45][45];
int vis[45][45];
int minn = 1600;
void bfs(int x, int y, int steps)
{
    if(x >= r||y >= c||x < 0||y < 0)
        return;
    if(x == r-1&&y == c-1) {
        if(minn > steps)
            minn = steps;
        return;
    }
    vis[x][y] = 1;
    for (int i = -1; i < 2; ++i)
        for (int j = -1; j < 2; ++j)
        if(abs(i)+abs(j) == 1&&!vis[x+i][y+j])
            bfs(x + i, y + j, steps+1);
}
int main()
{
    int steps = 1;
    cin >> r >> c;
    for (int i = 0; i < r; ++i)
        scanf("%s", map[i]);
    for (int i = 0; i < r; ++i)
        for (int j = 0; j < c; ++j)
            if(map[i][j] == '#')
                vis[i][j] = 1;
            else
                vis[i][j] = 0;
    bfs(0, 0, steps);
    cout << minn << endl;
    return 0;
}

但是宽搜明显快些,宽搜解决迷宫问题就是用队列先进先出的特点,一旦找到了结果一定是最短的(结合树状图自己理解),而深搜搜索的明显多些

宽搜代码如下

#include <iostream>
#include <queue>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cstdio>
using namespace std;
bool vis[45][45];
char map[45][45];
int n, m;
struct node{
    int x, y, step; //横纵坐标、到这个格子走了多少步
};
bool isok(int x, int y)
{
    if (x >= 0 && x < n && y >= 0 && y < n && !vis[x][y])
        return 1;
    return 0;
}
int main()
{
    while(scanf("%d%d",&n, &m) != EOF) {
        for (int i = 0; i < n; ++i)
            scanf("%s", map[i]);    //绘制地图
        memset(vis, 0, sizeof(vis));
        for (int i = 0; i < n; ++i)
            for (int j = 0; j < m; ++j)
                if(map[i][j] == '#')
                    vis[i][j] = 1;
                else
                    vis[i][j] = 0;
        //初始化
        queue<node> q;
        node point, newpoint;
        point.x = 0;
        point.y = 0;
        point.step = 1;

        //队列登场!
        q.push(point);
        while(!q.empty()) {
            point = q.front();
            q.pop();
            if(point.x == n-1&&point.y == m-1)
                cout << point.step << endl; //找到了直接输出,因为宽搜出来的结果一定是最短的
            for (int i = -1; i <= 1; ++i)
                for (int j = -1; j <= 1; ++j)
                    if(abs(i)+abs(j) == 1 && isok(point.x + i, point.y + j) ) {
                        newpoint.x = point.x + i;
                        newpoint.y = point.y + j;
                        vis[newpoint.x][newpoint.y] = 1;
                        newpoint.step = point.step + 1;
                        q.push(newpoint);
                    }
        }
    }
    return 0;
}