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的矩阵,s代表石头 .代表耕地,耕地可以种种子,问是否有方法让每块耕地都能种成种子,用过的土地便不能再用,就是有点像一笔画问题,思路就是从左上角开始搜,遇到土地就让其变成石头,让石头数+1;最后看石头数是不是等于n*m.我贴一个0ms过的代码,看一下代码
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
char c[8][8];
int i,n,j,k,l,m,vi,flag,a;
void dfs(int x,int y)
{
if(vi==n*m)//石头数等于总数,就标记flag=1;
{
flag=1;
return ;
}
if(x<0||x>m-1||y<0||y>n-1)//判断走到边界
return ;
if(c[x][y]!='.')//如果是石头
return ;
if(flag)//已经判断成功
return ;
a++;
if(a>1500)//这一点是0ms的关键如果次数达到这个情况,就不要浪费时间了,最差情况要判断31811177次
return ;
c[x][y]='S';//如果不是石头,就让它成为石头。 这一句不能和 最上边的判断石头数的交换 位置 ,调试了半天才调出来的,想想为什么
vi++;
dfs(x+1,y);
dfs(x-1,y);
dfs(x,y+1);
dfs(x,y-1);
vi--;//如果判断失败
c[x][y]='.';//让判断的点重新变回耕地
}
int main()
{
while(scanf("%d%d",&m,&n)&&(m||n))
{
a=0;
flag=0;
vi=0;
for(i=0;i<m;i++)
scanf("%s",c[i]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
if(c[i][j]=='S')//记录原来的石头数
vi++;
}
dfs(0,0);//从左上角开始搜
if(flag)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}