2100 Seeding【dfs】

ZOJ Problem Set - 2100
Seeding


Time Limit: 2 Seconds      Memory Limit: 65536 KB

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




题意:

有一个人,他有一块地,地上有一些石头,位置已知,然后要播种了,规定,已经播种过的地不能再次播种,也不能把机器开到农田之外,求这个人能否按要求把所有的土地耕种完毕.....


比较简单的 dfs 题,不过需要回溯......

本来自己也没有思路,后来朋友讲思路,算是明白了点,然后就按自己的方法写了.....

这个题可以算是图论里面的欧拉图,如果是欧拉图,那么就符合题意,因为这个题比较简单,所以这样用回溯法,很简单的就解决了这样的问题.........

回溯,因为计算机运行的时候语句是一条一条执行的,不管每条语句里面套了多少层循环和递归,都是执行到程序不能执行的时候,再一步步回到上一步来,所以,这个特性使得 多层dfs以及回溯得以实现,回溯吗?别觉得很高大上,只要当成把之前处理过的地方变成之前的样子就行!!


做这个题的时候,朋友的方法不错,但是我用自己的方法优化了一下,先求出总共可以耕种的地方,然后每一步dfs的时候都判断操作了多少地方,比较判断是否能完成题目要求的条件,如果不行,回溯的时候就要把统计的数值减掉,这样比着每一步都求操作了多少土地简化了很多,当然,要注意合适的时候开关变量特殊标记一下,这样跳出循环,不至于程序无限递归了....第一次接触回溯,感觉真的很不错,不过现在理解的还不够深,慢慢学习吧!


#include<stdio.h>
int n,m,kase,count,sum;char x[105][105];
void dfs(int a,int b)
{
	if(kase)
	{
		return;
	}
	if(x[a][b]=='S'||a<0||a>n-1||b<0||b>m-1)//不能运行的时候,也就是某条分支走到了尽头
	{
		if(sum==count)//如果操作完毕
		{
			kase=1;//开关状态改变
			return;
		}
		return;//否则退出,回溯到上一级
	}
	x[a][b]='S';
	++sum;
	dfs(a+1,b);dfs(a-1,b);//对前后左右四个方向进行 dfs 搜索....
	dfs(a,b-1);dfs(a,b+1);
	x[a][b]='.';//执行到这一句,证明不满足条件,已经回溯,那么,这个位置还恢复原来的状态,进行下一个分支的运算......
	--sum;//别忘统计的数量减少,因为已经回溯...
}
int main()
{
	int i,j;char y;
	while(scanf("%d%d",&n,&m),m||n)
	{
		count=0;kase=0;
		for(i=0;i<n;++i)
		{
			getchar();
			for(j=0;j<m;++j)
			{
				scanf("%c",&y);
				x[i][j]=y;
				if(y=='.')//为了统计个数,便于后面操作
				{
					++count;
				}
			}
		}
		sum=0;
		dfs(0,0);//从某个位置开始搜索...
		if(kase)//这个变量可以控制是否找到所需的状态和方式.....
		{
			printf("YES\n");
		}
		else
		{
			printf("NO\n");
		}
	}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值