【ACWing】844. 走迷宫

题目地址:

https://www.acwing.com/problem/content/846/

给定一个 m × n m\times n m×n二维 0 − 1 0-1 01矩阵, 0 0 0代表空地, 1 1 1代表障碍物。从 ( 1 , 1 ) (1,1) (1,1)出发,每次可以上下左右走一步,不能走到障碍物上。要走到 ( m , n ) (m,n) (m,n),问至少要走多少步。

数据范围:
1 ≤ n , m ≤ 1000 1\le n,m\le 1000 1n,m1000

用BFS即可。代码如下:

#include 
#include 

using namespace std;

typedef pair<int, int> PII;

const int N = 110;
int a[N][N];
bool visited[N][N];

int main() {
     
    int m, n;
    cin >> m >> n;

    for (int i = 1; i <= m; i++)
        for (int j = 1; j <= n; j++)
            cin >> a[i][j];

    if (m == 1 && n == 1) {
     
        cout << 0 << endl;
        return 0;
    }

    int res = 0;
    queue<PII> q;
    q.push(make_pair(1, 1));
    int d[] = {
     1, 0, -1, 0, 1};
    while (!q.empty()) {
     
        res++;
        int s = q.size();
        for (int i = 0; i < s; i++) {
     
            PII pair = q.front();
            q.pop();
            for (int j = 0; j < 4; j++) {
     
                int nextX = pair.first + d[j], nextY = pair.second + d[j + 1];
                if (nextX == m && nextY == n) {
     
                    cout << res << endl;
                    return 0;
                }

                if (1 <= nextX && nextX <= m && 1 <= nextY && nextY <= n && a[nextX][nextY] == 0 && !visited[nextX][nextY]) {
     
                    visited[nextX][nextY] = true;
                    q.push(make_pair(nextX, nextY));
                }
            }
        }
    }

    return 0;
}

时空复杂度 O ( m n ) O(mn) O(mn)

你可能感兴趣的:(AC,搜索,图论与网络,算法)