zoj 2100 Seeding

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

 题意:一个播种的机器,不可以走走过的区域,也不可以走有石头(S)的区域,问是否能走遍图中所有的不含石头的区域

题解:将走过的区域标记为有石头的区域,一直走如果可以走完即ans==s(走过的区域等于所有不含石头的区域)则返回输出YES否则回溯

        并清除标记,换其他路线继续搜索,直至结束

#include<stdio.h>
#include<string.h>
char map[10][10];
int n,m,ans,ok,s;
void dfs(int x,int y)
{
	int i,j;
	int move[4][2]={0,1,0,-1,1,0,-1,0};
	if(ans==s)
		ok=1;
	for(i=0;i<4;i++)
	{
		int tx=x+move[i][0];
		int ty=y+move[i][1];
		if(0<tx&&tx<=n&&0<ty&&ty<=m&&map[tx][ty]=='.')
	    {   
	        map[tx][ty]='S';
	        ans++;
	        dfs(tx,ty);
	        map[tx][ty]='.';
	        ans--;
	    }
	}
}
int main()
{
	int j,i;
	while(scanf("%d%d",&n,&m),n|m)
	{
		ans=0;
		ok=0;
		s=0;
		for(i=1;i<=n;i++)
		{
			getchar();
			for(j=1;j<=m;j++)
			{
				scanf("%c",&map[i][j]);
				if(map[i][j]=='.')
				s++;
			}
		}
		ans++;
		map[1][1]='S';
		dfs(1,1);
		if(!ok)
		printf("NO
");
		else
		printf("YES
");
	}
	return 0;
}

  

原文地址:https://www.cnblogs.com/tonghao/p/4702860.html