【ACWing】1112. Labyrinth

Subject address:

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

One day Extense accidentally walked into a maze while exploring the forest. The maze can be seen as n ∗ nn∗nn n grid points, each grid point is only2 2Two states,.and#, the former means that it is passable and the latter means it is not passable. At the same time, when Extense is at a certain grid point, he can only move to one of the adjacent grid points in one of the four directions, southeast, northwest (or up, down, left, and right). Extense wants to move from pointAAA goes to pointBBB , ask if it can be done without getting out of the maze. If either the starting point or the end point is impassable (#Yes), it is regarded as impossible. Note:AAA B B B is not necessarily two different points.

Input format:
No. 1 11 line is the number of groups of test datakkk followed bykkK group input. The first1 ofeach set of test data1 line is a positive integernnn , which means the scale of the maze isn ∗ nn∗nn n . Next is an ∗ nn∗nn n matrix, the elements in the matrix are.or#. The next line is4 44 integersha, la, hb, lb h_a,l_a,h_b,l_bha,la,hb,lb, Describe AAA is in the firstha h_ahaLine, la l_alaColumn, BBB is inhb h_bhbLine, lb l_blbColumn. Note that ha, la, hb, lb h_a,l_a,h_b,l_bha,la,hb,lbAll from 0 00 starts counting.

Output format:
kkk lines, each line of output corresponds to one input. If it can be done, it will output "YES", otherwise it will output "NO".

Data range:
1 ≤ n ≤ 100 1≤n≤1001n100

It can be directly from the starting point DFS, if the end point can be searched, it will output YES, otherwise it will output NO. Pay attention to #the situation where the starting point or the end point needs to be judged . code show as below:

#include <iostream>
#include <cstring>
using namespace std;

const int N = 110, d[] = {
    
    1, 0, -1, 0, 1};
char a[N][N];
bool st[N][N];
int n;
int sx, sy, ex, ey;

bool dfs(int x, int y) {
    
    
    if (x == ex && y == ey) return true;

    st[x][y] = true;
    for (int i = 0; i < 4; i++) {
    
    
        int nx = x + d[i], ny = y + d[i + 1];
        if (0 <= nx && nx < n && 0 <= ny && ny < n && a[nx][ny] != '#' && !st[nx][ny]) 
            if (dfs(nx, ny)) return true;
    }

    return false;
}

int main() {
    
    
    int T;
    cin >> T;
    while (T--) {
    
    
        cin >> n;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                cin >> a[i][j];
        cin >> sx >> sy >> ex >> ey;

        memset(st, false, sizeof st);

        bool res = false;
        if (a[sx][sy] == '#' || a[ex][ey] == '#') res = false;
        else res = dfs(sx, sy);

        cout << (res ? "YES" : "NO") << endl;
    }

    return 0;
}

Time and space complexity of each case O (n 2) O(n^2)O ( n2)

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/114637223