bfs迷宮問題(確定起點終點類型)模板題

給定一個n*m大小的迷宮,其中*代表不可通過的牆壁,而.代表平地,S代表起點,T代表終點。

移動過程中,如果當前位置是(x,y)(下標從0開始),且每次只能前往上下左右四個位置的平地。

求從起點S到達終點T的最少步數。

#include <iostream>
#include <bitset>
#include <algorithm>
#include <cmath>
#include <ctype.h>
#include <string>
#include <cstring>
#include <cstdio>
#include <set>
#include <cstdio>
#include <fstream>
#include <deque>
#include <vector>
#include <queue>
#include <map>
#include <stack>
#include <iomanip>
#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<node> 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
*/

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章