[Shik and Stone] 搜索/结论

Descriptoon

We have a grid of H rows and W columns. Initially, there is a stone in the top left cell. Shik is trying to move the stone to the bottom right cell. In each step, he can move the stone one cell to its left, up, right, or down (if such cell exists). It is possible that the stone visits a cell multiple times (including the bottom right and the top left cell).

You are given a matrix of characters aij (1≤i≤H, 1≤j≤W). After Shik completes all moving actions, aij is '#' if the stone had ever located at the i-th row and the j-th column during the process of moving. Otherwise, aij is .. Please determine whether it is possible that Shik only uses right and down moves in all steps.

Constraints
2≤H,W≤8
ai,j is either '#' or '.'.
There exists a valid sequence of moves for Shik to generate the map a.

Solution

数据范围很小,直接dfs

Note

一开始没有读好题,没看到had ever located,应该统计有无通过所有#的解
Update 此题还有直接统计#个数的解法,也很好理解,题目保证了每个#都会经过一次,所以从左上角到右下角只能走h+w-2次,只需要看#的个数是不是h+w-2

Code

#include<bits/stdc++.h>
#define mem(a,b) memset(a,b,sizeof(a))
typedef long long ll;
typedef unsigned long long ull;
using namespace std;

int H, W, sum;
char ma[41][41];

bool f = false;

inline void DFS(int x, int y, int st) {
//  cout << x << " " << y << " "<< ma[x][y]<< endl;
    if (x == H && y == W && st + 1 == sum) {
        //cout << "DE" << endl;
        f = true;
        return;
    }
    if (x+1 <= H && ma[x+1][y] == '#')
    DFS(x+1,y, st+1);
    if (y+1 <= W && ma[x][y+1] == '#') 
    DFS(x, y+1,st+1);
}

int main() {
    //freopen("test.txt", "r", stdin);
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin >> H >> W;
    for (int i = 1; i <= H; i++) 
        for (int j = 1; j <= W; j++){
        cin >> ma[i][j];
        if (ma[i][j] == '#') sum++;
    }
    DFS(1,1,0);
    if (f) {
        cout << "Possible";
    } else {
        cout << "Impossible";
    }

    return 0;
}

原文链接: https://www.cnblogs.com/ez4zzw/p/12595857.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    [Shik and Stone] 搜索/结论

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/338668

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午11:43
下一篇 2023年3月1日 下午11:43

相关推荐