zoukankan      html  css  js  c++  java
  • [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;
    }
    
    
  • 相关阅读:
    mac creact-react-app 时包 gyp-error
    JAVA,JDBC报错Access denied for user '"root"'@'localhost
    JAVA,JDBC连接数据库报错:No suitable driver found for "jdbc:mysql://localhost:3306
    JAVA,反射使用demo,通过读取配置文件创建类,调用方法
    JAVA,反射获取class对象的3种方式
    python获取当前时间距离指定时间相差的秒值
    JAVA,字节流文件读写
    JAVA,反射常用方法
    JAVA,字符流读写,flush和close的区别
    JAVA,字符流文件读写
  • 原文地址:https://www.cnblogs.com/ez4zzw/p/12595857.html
Copyright © 2011-2022 走看看