首页 > 其他 > 详细

poj 3009 DFS水题

时间:2014-03-21 13:26:17      阅读:247      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
/*
题意:
给出一个矩形地面,且地面很滑,向某个方向走只能一直走直到撞到block才能停下,即在block的旁边停下,而且
一旦撞到则该block消失;该矩形框的四周相当于没有block,会直接滑走;如果下一格就会遇到block,则这个方向
也不能走;给出起点和终点,求从起点到终点(经过也算)最少需要多少步,一个方向滑一次算作一步。

题解:DFS
某大牛说一看到block会消失,铁定DFS(我持保留意见),果然,水题一枚,直接深搜四个方向。
*/
#include <cstdio>
#include <algorithm>

#define Max 25

int m[Max][Max];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int w,h,ans;

void dfs(int x, int y, int depth)
{
    if (depth >= 10)
        return ;
    int nx,ny;
    for(int i=0; i<4; i++)
    {
        nx = x+dir[i][0];
        ny = y+dir[i][1];
        if (m[nx][ny] != 1)  // 判断是否下一格就是block
        {
            while (1<=nx && nx<=h && 1<=ny && ny<=w)  // 保证不会滑出方框外
            {
                if (m[nx][ny] == 3)  // 到终点
                {
                    if (ans != -1)
                        ans = std::min(depth+1,ans);
                    else
                        ans = depth+1;
                    return ;
                }
                if (m[nx][ny] == 1)  // 撞到了block
                {
                    m[nx][ny] = 0;
                    dfs(nx-dir[i][0],ny-dir[i][1],depth+1); // 这里不用担心退后一步会回到原地,因为已经保证了
                                                            // 是能走,则肯定是走过一个0格之后再走到这一格
                    m[nx][ny] = 1;
                    break;
                }
                // 用循环模拟向某个方向一直走
                nx += dir[i][0];
                ny += dir[i][1];
            }
        }
    }
}

int main(void)
{
    while (~scanf("%d%d",&w,&h) && w+h)
    {
        for(int i=1; i<=h; i++)
        {
            for(int j=1; j<=w; j++)
            {
                scanf("%d",&m[i][j]);
            }
        }
        ans = -1;
        for(int i=1; i<=h; i++)
        {
            int j;
            for(j=1; j<=w; j++)
            {
                if (m[i][j] == 2)  // 找到起点就开始搜
                {
                    m[i][j] = 0;
                    dfs(i,j,0);
                    break;
                }
            }
            if (j <= w)
                break;
        }
        printf("%d\n",ans);
    }
    return 0;
}
bubuko.com,布布扣

poj 3009 DFS水题,布布扣,bubuko.com

poj 3009 DFS水题

原文:http://www.cnblogs.com/toufu/p/3614923.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!