您的位置:首页 > 其它

poj 3009 Curling 2.0(dfs)

2014-07-31 19:26 447 查看
Curling 2.0

Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 11353Accepted: 4804
Description

On Planet MM-21, after their Olympic games this year, curling is getting popular. But the rules are somewhat different from ours. The game is played on an ice game board on which a square mesh is marked. They use only a single stone. The purpose of the game is to lead the stone from the start to the goal with the minimum number of moves.

Fig. 1 shows an example of a game board. Some squares may be occupied with blocks. There are two special squares namely the start and the goal, which are not occupied with blocks. (These two squares are distinct.) Once the stone begins to move, it will proceed until it hits a block. In order to bring the stone to the goal, you may have to stop the stone by hitting it against a block, and throw again.

#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int N = 25;
int Map

,sx,sy,ex,ey,t;
int ans,m,n;
void dfs(int x,int y,int step)
{
int i,j;
if(step>10)
return ;
if(x == ex  && y ==ey && step<=ans )
{
ans=step;
}
i=1;
while(x-i>0 && Map[x-i][y]!=1)//向上查找,如果下一个是1,直接跳出
{
if(Map[x-i][y]==3)
{
dfs(x-i,y,step+1);
}
else if(Map[x-i-1][y]==1)//判断下下一个,如果是1,变成0,深搜当前的坐标
{  t=Map[x-i-1][y];
Map[x-i-1][y]=0;
dfs(x-i,y,step+1);
Map[x-i-1][y]=t;
}
i++;
}
i=1;
while(x+i<=m && Map[x+i][y]!=1)//向下
{
if(Map[x+i][y]==3)
{
dfs(x+i,y,step+1);
}
if(Map[x+i+1][y] == 1)
{   t=Map[x+i+1][y];
Map[x+i+1][y]=0;
dfs(x+i,y,step+1);
Map[x+i+1][y]=t;
}
i++;
}
j=1;
while(y-j>0 && Map[x][y-j]!=1)//向左
{
if(Map[x][y-j]==3)
dfs(x,y-j,step+1);
if(Map[x][y-j-1]==1)
{   t=Map[x][y-j-1];
Map[x][y-j-1]=0;
dfs(x,y-j,step+1);
Map[x][y-j-1]=t;
}
j++;
}
j=1;
while(y+j<=n && Map[x][y+j]!=1)//向右
{
if(Map[x][y+j] == 3)
{
dfs(x,y+j,step+1);
}
if(Map[x][y+j+1]==1)
{   t=Map[x][y+j+1];
Map[x][y+j+1]=0;
dfs(x,y+j,step+1);
Map[x][y+j+1]=t;
}
j++;
}
}
int main()
{
while(cin>>n>>m && m+n)
{
memset(Map,0,sizeof(Map));
for(int i=1; i<=m; i++)
for(int j=1; j<=n; j++)
{
scanf("%d",&Map[i][j]);
if(Map[i][j]==2)
{sx=i,sy=j;}
else if(Map[i][j] == 3)
{ex=i;ey=j;}
}
ans=15;//初始化ans>10,以便于下面的判断
dfs(sx,sy,0);
if(ans<=10)
printf("%d\n",ans);
else printf("-1\n");
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: