• [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;
    }
    
    
  • 相关阅读:
    IO基础
    集合框架
    数据结构基础
    进程和线程
    matlab绘制三维图形
    matlab figure 窗口最大化
    Matlab中的fread函数
    matlab中fopen 和 fprintf函数总结
    matlab中findstr,strfind,strcmp,strncmp区别与联系
    matlab取消和添加注释以及一些快捷键
  • 原文地址:https://www.cnblogs.com/ez4zzw/p/12595857.html
Copyright © 2020-2023  润新知