[AcWing 1112] 迷宫

image
image

DFS + 去重

复杂度 \(O(n^{2})\)


点击查看代码
#include<bits/stdc++.h>

using namespace std;

typedef long long LL;

const int N = 100 + 10;

int n;
char g[N][N];
int xa, ya, xb, yb;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
bool st[N][N];

bool dfs(int x, int y)
{
    if (g[x][y] == '#')
        return false;
    if (x == xb && y == yb)
        return true;
    st[x][y] = true;
    for (int i = 0; i < 4; i ++) {
        int a = x + dx[i], b = y + dy[i];
        if (a < 0 || a >= n || b < 0 || b >= n || st[a][b])
            continue;
        if (dfs(a, b))
            return true;
    }
    return false;
}

void solve()
{
    cin >> n;
    for (int i = 0; i < n; i ++)
        for (int j = 0; j < n; j ++)
            cin >> g[i][j];
    cin >> xa >> ya >> xb >> yb;
    memset(st, false, sizeof st);
    bool ok = dfs(xa, ya);
    cout << (ok ? "YES" : "NO") << endl;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int T;
    cin >> T;
    while (T --) {
        solve();
    }

    // solve();

    return 0;
}

  1. 类比 \(BFS\) 走迷宫,\(DFS\) 需要写成递归的形式,用 \(bool\) 类型的 \(st\) 数组用来判断格点是否被搜过,避免重复搜索
posted @ 2022-08-07 22:19  wKingYu  阅读(16)  评论(0编辑  收藏  举报