Curling 2.0 POJ 3009

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值