一开始做就是按照普通的递归,一步一步递归,发现结果一直是YES,后来发现理解错了,如果直接递归算出来的是相邻的地的块数,没有考虑走的路线和方向,但此题需要一步一步的走,如果走到最后发现没法播种了,要返回前一步,然后把对应的刚刚播种的土地再回复原样!
Seeding
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 86 Accepted Submission(s) : 39
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
wa码
#include<stdio.h>
#define max 1001
char a[max][max];
int x,y,m,n;
int cnt,cont;
void dfs(int x,int y)
{
if(x<1||x>m||y<1||y>n)
return;
if(a[x][y]=='S')
return;
a[x][y]=='S';
cnt++;
dfs(x,y-1);
//dfs(x+1,y);
dfs(x-1,y);
//dfs(x,y+1);
}
int main()
{
int i,j;
while(scanf("%d%d",&m,&n),m|n)
{
for(i=1;i<=m;i++)
{
getchar();
for(j=1;j<=n;j++)
scanf(" %c",&a[i][j]);
}
int cnt=0,cont=0;
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
if(a[i][j]=='S')
cont++;
}
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
if(a[i][j]=='.')
{
x=i;
y=j;
dfs(x,y);
}
}
if(cnt+cont==m*n)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
ac码
#include<stdio.h>
#define max 1001
char a[max][max];
int x,y,m,n;
int flag,cont;
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
void dfs(int x,int y)
{
if(x<1||x>m||y<1||y>n)
return ;
if(a[x][y]=='S')
return ;
// if(flag)
// return;
a[x][y] = 'S';
cont++;
if(cont == n*m)//判断是否已经全部播种完
{
flag=1;
return;
}
dfs(x+1,y); //四个方向搜索
dfs(x-1,y);
dfs(x,y+1);
dfs(x,y-1);
cont--; //回溯退一步,计数器减一
a[x][y]='.'; //把播种的S回复为原来的.
}
int main()
{
int i,j;
while(scanf("%d%d",&m,&n),m|n)
{
for(i=1;i<=m;i++)
{
getchar();
for(j=1;j<=n;j++)
scanf(" %c",&a[i][j]);
}
cont=0;
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
if(a[i][j]=='S')
cont++;
}
flag=0;
dfs(1,1);
if(flag)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}