Algorithm 13——Solve the minimum number of steps to get out of the maze (queue implementation BFS problem)

Description of the problem:
 emsp;Given a maze of size n*m, where * represents an impassable wall, . represents a flat bottom, S represents the starting point, and T represents the end point. During the movement, if the current position is (x,y) (the subscript starts from 0), and each time it can only go up, down, left, and right (x+1,y)(x-1,y),(x,y+1 ), (x, y-1) four positions of flat ground, find the minimum number of steps from S to T.

.....
.*.*.
.*S*.
.***.
...T*

In the above case, S is (2,2), T is (4,3)

Idea:
  Since the minimum number of steps is sought, and BFS traverses through the order of the layers, the number of layers traversed can be recorded from S, then the number of layers when reaching T is the minimum number of steps solved.

code:

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn = 100;
struct node{
    int x,y;//位置
    int step;//到终点的最少步数,即层数
}S,T,Node;

int n,m;//行和列
char maze[maxn][maxn];//迷宫信息
bool inq[maxn][maxn] = {false};//记录是否已经入队
int X[4]={0,0,1,-1};
int Y[4]={1,-1,0,0};

//检测位置(x,y)是否有效
bool test(int x, int y){
    if(x >= n || x < 0 || y >= m || y < 0)
        return false;
    if(maze[x][y]=='*')
        return false;
    if(inq[x][y]==true)
        return false;
    return true;
}

int BFS(){
    queue<node> q;
    q.push(S);
    while(!q.empty()){
        node top = q.front();//取出队首元素
        q.pop();
        if(top.x == T.x && top.y == T.y)
            return top.step;//已经到达终点
        for(int i = 0 ; i < 4 ; i++){
            int newX = top.x + X[i];
            int newY = top.y + Y[i];
            if(test(newX,newY)){
                //如果位置有效
                Node.x = newX;
                Node.y = newY;
                Node.step = top.step+1;
                q.push(Node);
                inq[newX][newY] = true;
            }
        }
    }
    return -1;
}

int main(){
    scanf("%d%d",&n,&m);
    for(int i = 0 ; i < n ; i++){
        getchar();//过滤掉每行的换行字符
        for(int j = 0 ; j < m ; j++){
            maze[i][j] = getchar();
        }
        maze[i][m+1] = '\0';
    }
    scanf("%d%d%d%d",&S.x,&S.y,&T.x,&T.y);
    S.step = 0;
    printf("%d\n",BFS());
    return 0;
}

insert image description here

Guess you like

Origin blog.csdn.net/weixin_46025531/article/details/122854264