其他分享
首页 > 其他分享> > 题解 AcWing 1112. 迷宫 & AcWing 1113. 红与黑

题解 AcWing 1112. 迷宫 & AcWing 1113. 红与黑

作者:互联网

题目描述

因为这两题都比较简单并且很相似所以这里就不再复述题意了。

AcWing 1112. 迷宫 & AcWing 1113. 红与黑

Solution

思路都基本一样:标记所有的障碍点,找到起点,从起点开始 DFS 。

有个小技巧:因为走过的点和障碍点可以看成是同一个东西,所以并不需要另外开一个数组存储每个点是不是障碍点,直接标记这些点走过就行了。但是第一题需要先判断起点或者终点是不是障碍点

注意多测要清空。

AcWing 1112. 迷宫:

#include <cstdio>
#include <cstring>
#include <cctype>
#include <algorithm>
#include <iostream>
using namespace std;
const int N = 105;
bool vis[N][N];
const int dx[] = {0 ,-1 ,1 ,0 ,0} ,dy[] = {0 ,0 ,0 ,-1 ,1};
int n;
inline void dfs(int x ,int y) {
    vis[x][y] = true;
    for (int i = 1; i <= 4; i++) {
        int tx = x + dx[i] ,ty = y + dy[i];
        if (tx < 1 || ty < 1 || tx > n || ty > n || vis[tx][ty]) continue;
        dfs(tx ,ty);
    }
}
char s[N];
signed main() {
    int T; scanf("%d" ,&T);
    while (T--) {
        scanf("%d" ,&n);
        for (int i = 1; i <= n; i++) {
            scanf("%s" ,s + 1);
            for (int j = 1; j <= n; j++)
                if (s[j] == '#') vis[i][j] = true;
        }
        int a ,b ,c ,d;
        scanf("%d%d%d%d" ,&a ,&b ,&c ,&d);
        a++; b++; c++; d++;
        if (!vis[a][b] && !vis[c][d]) {
            dfs(a ,b);
            if (vis[c][d]) puts("YES");
            else puts("NO");
        }
        else puts("NO");
        memset(vis ,false ,sizeof(vis));
    }
}

AcWing 1113. 红与黑

#include <cstdio>
#include <cstring>
#include <cctype>
#include <algorithm>
#include <iostream>
using namespace std;
inline int read() {
    int num = 0 ,f = 1; char c = getchar();
    while (!isdigit(c)) f = c == '-' ? -1 : f ,c = getchar();
    while (isdigit(c)) num = (num << 1) + (num << 3) + (c ^ 48) ,c = getchar();
    return num * f;
}
const int N = 25;
bool vis[N][N];
const int dx[] = {0 ,-1 ,1 ,0 ,0} ,dy[] = {0 ,0 ,0 ,-1 ,1};
int n ,m;
inline int dfs(int x ,int y) {
    int ans = 1;
    vis[x][y] = true;
    for (int i = 1; i <= 4; i++) {
        int tx = x + dx[i] ,ty = y + dy[i];
        if (tx < 1 || ty < 1 || tx > n || ty > m || vis[tx][ty]) continue;
        ans += dfs(tx ,ty);
    }
    return ans;
}
char s[N];
signed main() {
    while ((m = read() ,n = read()) ,n || m) {
        int sx ,sy;
        for (int i = 1; i <= n; i++) {
            scanf("%s" ,s + 1);
            for (int j = 1; j <= m; j++)
                if (s[j] == '@') sx = i ,sy = j;
                else if (s[j] == '#') vis[i][j] = true;
        }
        printf("%d\n" ,dfs(sx ,sy));
        memset(vis ,0 ,sizeof(vis));
    }
    return 0;
}

标签:tx,ty,int,题解,vis,1113,include,AcWing
来源: https://www.cnblogs.com/Dragon-Skies/p/14716176.html