搜索与回溯系列十九 zoj 2100 播种

2020-02-23  本文已影响0人  徐慵仙

题目

https://zoj.pintia.cn/problem-sets/91827364500/problems/91827365599

Seeding

It is spring time and farmers have to plant seeds in the field. Tom has a nice field, which is a rectangle with n * m squares. There are big stones in some of the squares.
Tom has a seeding-machine. At the beginning, the machine lies in the top left corner of the field. After the machine finishes one square, Tom drives it into an adjacent square, and continues seeding. In order to protect the machine, Tom will not drive it into a square that contains stones. It is not allowed to drive the machine into a square that been seeded before, either.

Tom wants to seed all the squares that do not contain stones. Is it possible?

Input

The first line of each test case contains two integers n and m that denote the size of the field. (1 < n, m < 7) The next n lines give the field, each of which contains m characters. 'S' is a square with stones, and '.' is a square without stones.

Input is terminated with two 0's. This case is not to be processed.

Output

For each test case, print "YES" if Tom can make it, or "NO" otherwise.

Sample Input

4 4
.S..
.S..
....
....
4 4
....
...S
....
...S
0 0

Sample Output

YES
NO

简译

简单翻一下就是,汤姆有一块好地,是个n*m个小块组成的的矩形,但这块地里有可能有石头。春天到了,汤姆买了个播种机,他这人特别轴,得从左上角开始耕田,然后还得一次性种完,还不能碰到石头。让你帮写个程序看能不能实现。

简析

典型的二维矩阵搜索问题,可参考

代码

#include <iostream>
#include <cstring>
using namespace std;
int vis[200][8]={0};
int mv[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int n,m;
int tian;
int flag;
void search(int x,int y,int k){
    if(k==tian){
        flag=1;
        return;
    }
    for(int i=0;i<4;i++){
        int xx=x+mv[i][0];
        int yy=y+mv[i][1];
        if(vis[xx][yy]!=1&&xx>=0&&xx<n&&yy>=0&&yy<m){
            vis[xx][yy]=1;
            search(xx,yy,k+1);
            vis[xx][yy]=0;
        }
    }
}
int main(){
    char temp;
    while(1){
        cin>>n>>m;
        if(n==0&&m==0) break;
        flag=0;
        tian=0;
        memset(vis, 0, sizeof(vis));
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                cin>>temp;
                if(temp=='S') vis[i][j]=1;
                else tian++;
            }
        }
        vis[0][0]=1;
        search(0,0,1);
        if(flag) cout<<"YES"<<endl;
        else cout<<"NO"<<endl;
    }
}

上一篇 下一篇

猜你喜欢

热点阅读