zcmu1275: Seeding

Title link: https://acm.zcmu.edu.cn/JudgeOnline/problem.php?id=1275

Topic

A lawn with a length of n and a width of m, "." means weeds, "S" means stones, now we start weeding from position (1,1), and you can move up and down each time, but the stone acts as an obstacle to block you from moving forward. Should choose a detour. Ask if you can finally clean up all the weeds.

Ideas

Run dfs from the position (1, 1) to see if the maximum depth is n*m-cnt, and cnt is the number of stones. It is also necessary to judge whether the position (1,1) is a stone.

ac code

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ok(x, y) x >= 1 && x <= n && y >= 1 && y <= m
int dx[] = {0, 0, -1, 1};
int dy[] = {-1, 1, 0, 0};
int vis[10][10];
char a[10][10];
int n, m, cnt, flag;
void dfs(int x, int y, int dep){
    if(dep == cnt){
        flag = 1;
        return;
    }
    for(int i = 0; i < 4; i ++){
        int tx = x + dx[i];
        int ty = y + dy[i];
        if(ok(tx, ty) && !vis[tx][ty] && a[tx][ty] != 'S'){
            vis[tx][ty] = 1;
            dfs(tx, ty, dep + 1);
            if(flag) return;
            vis[tx][ty] = 0;
        }
    }
}
int main(){
    while(~scanf("%d%d", &n, &m)){
        if(n + m == 0) break;
        cnt = n * m;
        memset(vis, 0, sizeof(vis));
        for(int i = 1; i <= n; i ++) {
            scanf("%s", a[i] + 1);
            for(int j = 1; j <= m; j ++){
                if(a[i][j] == 'S') cnt --;
            }
        }
        if(a[1][1] == 'S'){
            puts("NO");
            continue;
        }
        flag = 0;
        vis[1][1] = 1;
        dfs(1, 1, 1);
        if(flag) puts("YES");
        else puts("NO");
    }
    return 0;
}

 

Guess you like

Origin blog.csdn.net/weixin_43911947/article/details/113280865