Curling 2.0 POJ 3009

来源:互联网 发布:机械矩阵沙盘排名 编辑:程序博客网 时间:2024/06/06 12:28

1、题目类型:模拟、迷宫、DFS。

2、解题思路:(1)将输入转换为Maze[][],并记录开始位置2,结束位置3;(2)模拟,按题意要求DFS寻找最优解。

3、注意事项:注意DFS但step大于10时返回,否则程序超时;DFS中发生碰撞后,注意更新Maze[][]。

4、实现方法:


#include<iostream>#include<queue>using namespace std;struct Point{    int x,y;    int step;};Point start,end;int col,row,ans,flag,Maze[30][30];int dir[4][2]={{-1,0},{0,1},{1,0},{0,-1}};void Init(){    int i,j;    memset(Maze,0,sizeof(Maze));    ans=11;    flag=0;    for(i=0;i<row;i++)    {        for(j=0;j<col;j++)        {            cin>>Maze[i][j];            if(Maze[i][j]==2)            {                start.x=i;                start.y=j;                Maze[i][j]=0;            }            if(Maze[i][j]==3)            {                end.x=i;                end.y=j;            }        }    }}void DFS(Point cur,int step){    if(step>10)        return ;    for(int i=0;i<4;i++)    {        int x,y;        int j=0;        x=cur.x+dir[i][0];        y=cur.y+dir[i][1];        while(x>=0&&x<row&&y>=0&&y<col&&Maze[x][y]==0)        {            x+=dir[i][0];            y+=dir[i][1];            j++;        }        if(x>=0&&x<row&&y>=0&&y<col&&Maze[x][y]==3)        {            ans=ans>step+1?step+1:ans;            if(ans<=10)                flag=1;            return ;        }        if(j>0)        {            if(x>=0&&x<row&&y>=0&&y<col)            {                Point p;                p.x=x-dir[i][0];                p.y=y-dir[i][1];                Maze[x][y]=0;                DFS(p,step+1);                Maze[x][y]=1;            }        }    }}int main(){    while(cin>>col>>row)    {        if(col==0&&row==0)            break;        Init();        DFS(start,0);        if(flag)            cout<<ans<<endl;        else            cout<<"-1"<<endl;    }    return 0;}

0 0