编程语言
首页 > 编程语言> > 算法笔记-BFS-迷宫问题

算法笔记-BFS-迷宫问题

作者:互联网

迷宫问题

 

 

代码:

#include <bits/stdc++.h>

/*
5 5
.....
.*.*.
.*S*.
.***.
...T*
2 2 4 3
*/

using namespace std;

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

const int maxn = 100;

int n, m;

char matrix[maxn][maxn];
bool inq[maxn][maxn] = {false};
int dx[4] = {0, 0, 1, -1}, dy[4] = {1, -1, 0, 0};

bool judge(int x, int y){
    if(x<0||x>=n||y<0||y>=m) return false;
    if(matrix[x][y]=='*'||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 + dx[i];
            int newY = top.y + dy[i];
            if(judge(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 x=0; x<n; x++){
        getchar();
        for(int y=0; y<m; y++)
            matrix[x][y] = getchar();
    }
    scanf("%d%d%d%d", &S.x, &S.y, &T.x, &T.y);
    S.step = 0;
    printf("%d\n", BFS());
	return 0;
}

 

标签:return,int,top,迷宫,inq,BFS,算法,maxn,false
来源: https://blog.csdn.net/qq_41966660/article/details/112981159