bfs迷宫问题(确定起点终点类型)模板题

给定一个n*m大小的迷宫,其中*代表不可通过的墙壁,而.代表平地,S代表起点,T代表终点。

移动过程中,如果当前位置是(x,y)(下标从0开始),且每次只能前往上下左右四个位置的平地。

求从起点S到达终点T的最少步数。

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define SIS std::ios::sync_with_stdio(false)
#define ll long long
#define INF 0x3f3f3f3f
const int mod = 1e9 + 7;
const double esp = 1e-5;
const double PI = 3.141592653589793238462643383279;
using namespace std;
const int N = 1e7 + 5;
const int maxn = 1 << 20;
ll powmod(ll a, ll b) { ll res = 1; a %= mod; while (b >= 0); for (; b; b >>= 1) { if (b & 1)res = res * a % mod; a = a * a % mod; }return res; }
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
/*void chafen(int l, int r, int k) {//差分函数
    p[l] += k;
    p[r + 1] -= k;
}*/
/*********************************************************/
bool vis[105][105];
char a[105][105];
int x[4] = { -1,0,1,0 };
int y[4] = { 0,1,0,-1 };
int u1, v1, u2, v2;
int n, m;
struct node {
    int x;
    int y;
    int step;
};
bool test(int x, int y) {
    if (x < 0 || x >= n || y < 0 || y >= m)
        return false;
    if (a[x][y] == '*' || vis[x][y])
        return false;
    return true;
}
int bfs() {
    queue q;
    node p;//起点
    p.x = u1; p.y = v1;
    p.step = 0;
    q.push(p);
    vis[u1][v1] = true;
    while (!q.empty()) {
        node p1 = q.front();
        q.pop();
        if (p1.x == u2 && p1.y == v2)
            return p1.step;
        node t;
        for (int i = 0; i < 4; i++) {
            t.x = p1.x + x[i];
            t.y = p1.y + y[i];
            t.step = p1.step + 1;
            if (test(t.x,t.y)) {
                q.push(t);
                vis[t.x][t.y] = true;
            }
        }
    }
    return -1;
}
int main()
{
    cin >> n >> m;
    memset(vis, false, sizeof(vis));
    for (int i = 0; i < n; i++) {
        getchar();
        for (int j = 0; j < m; j++) {
            cin >> a[i][j];
            if (a[i][j] == 'S') {
                u1 = i;
                v1 = j;
            }
            if (a[i][j] == 'T') {
                u2 = i;
                v2 = j;
            }
        }
    }
        
    int a1, a2, a3, a4;
    cin >> a1 >> a2 >> a3 >> a4;
    cout << bfs() << endl;
    return 0;
}
/*
5 5
.....
.*.*.
.*S*.
.***.
...T*
2 2 4 3
*/

 

你可能感兴趣的:(DFS&&BFS)