c ++ maze search (broad search)

c ++ maze search (broad search)

Title Description

Maze game, I believe we have heard, we now express a maze with a matrix of n * m, for example:

S.X.
..X.
..XD
....

Where 'S' represents the starting point, 'D' indicates the end, 'X' indicates that the location for the wall, can not go, '' is passable. You can only move one step to the "up and down" four directions.
Your task is to determine the x in the step (less than or equal x), can come to the end from the beginning.

Entry

The first line of the input three numbers nmx, respectively, the size and the number of steps maze. (1 <n, m <7; 0 <x <50)

Now enter a matrix of n * m, describe the state of the maze.

Export

Determine whether the end can come from a starting point in the x-step, and if so, output "YES", otherwise a "NO".

Sample input

3 4 5
S.X.
..X.
...D

Sample Output

YES

Ado, directly on the code

AC Code

#include <bits/stdc++.h>
using namespace std;
int n,m,z,f,e;//e是入队的下标 f 是出队的下标
struct point {//结构体 
    int x,y,step;
};
int dx[4]= {1,-1,0,0};//dx[] + dy[] 代表小人走的4个方向可达的点 
int dy[4]= {0,0,-1,1};
point q[100],s,t;//q是队列 s是起点 t是终点 
char g[10][10];//整个队列 (迷宫)即二位数组 
bool used[10][10];
int main()
{
    scanf("%d %d %d",&n,&m,&z);//输入 
    for(int i=0; i<=n-1; i++) {//输入 
        scanf("%s",g[i]);//scanf
        for(int j=0; j<=m-1; j++) {//获取起点和终点的 x 和 y 坐标 
            if(g[i][j] == 'S') { 
                s.x=i,s.y=j,s.step=0;
            } else if(g[i][j]=='D')
                t.x=i,t.y=j;
        }
    }
    memset(used ,0,sizeof(used)); //memset
    q[1]=s,f=1,e=1,used[s.x][s.y]=1;// 把起点入队 
////////////////////////////////Strat to BFS///////////////////////////////////////////
    while(f<=e) {//保证不越界 
        point u=q[f++];//选定的元素 
        for(int i=0; i<4; i++) {
            point v;
            v.x=u.x+dx[i],v.y=u.y+dy[i],v.step=u.step+1;
            if(v.x<0||v.x>=n||v.y<0||v.y>m)continue;//如果出了迷宫 
            if(used[v.x][v.y]==1)continue;//如果已经走过 
            if(v.step>z)continue;//如果 步数超过规定 
            if(g[v.x][v.y]=='X')continue;//如果撞墙 
            if(v.x==t.x&&v.y==t.y) {//如果找到出口
                cout << v.step << endl;//直接输出在退出 
                cout<<"YES"<<endl;
                return 0;
            }
            e++;//直接入队 
            q[e]=v;
            used[v.x][v.y]=1;
        }
    }
    cout<<"NO"<<endl;
    return 0;
}

bfs ideas summarize:
step1: first find out the number of all eligible rules, by the rules of the maze and can not pass through the wall, can not exceed the boundaries of the maze, can not exceed 5 steps to filter
step2: the effective number into the team, the team carried out simultaneously Compare whether the end
step3: to reach the end of the output yes

Guess you like

Origin www.cnblogs.com/LJA001162/p/11184237.html