Seeding(dfs)

Seeding

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 101   Accepted Submission(s) : 52
Problem Description
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

 题解:跟南阳最小步数差不多,这个是耕过的地就不再耕了,所以带个回溯,记录步数,如果走的步数等于‘.’的总个数就符合找不到就不对;

代码:

 1 #include<stdio.h>
 2 int m,n,tot,nos;
 3 bool flag;
 4 char table[7][7];
 5 void dfs(int x,int y){
 6     //max=tot>max?tot:max;
 7     if(table[x][y]=='S'||x<0||x>=n||y>=m||y<0)return;
 8     table[x][y]='S';
 9     tot++;
10     if(tot==nos){
11         flag=true;
12         return;
13     }
14     dfs(x+1,y);
15     dfs(x,y+1);
16     dfs(x-1,y);
17     dfs(x,y-1);
18     tot--;//回溯;
19     table[x][y]='.';//回溯;
20     return ;
21 }
22 int main(){
23     int x,y,i,j;
24     while(~scanf("%d%d",&n,&m),n||m){//max=0;
25         for(x=0;x<n;x++)scanf("%s",table[x]);
26         nos=0;tot=0;flag=false;
27         for(x=0;x<n;x++){
28             for(y=0;y<m;y++){
29                 if(table[x][y]=='.'){
30                     nos++;
31                     if(nos==1)i=x,j=y;
32                 }
33             }
34         }
35         dfs(i,j);
36     //    printf("%d\n",max);
37         //for(x=0;x<n;x++)printf("%s\n",table[x]);
38         if(flag)puts("YES");
39         else puts("NO");
40     }
41     return 0;
42 } 

 

posted @ 2015-08-04 23:02  handsomecui  阅读(351)  评论(0编辑  收藏  举报