码迷,mamicode.com
首页 > 其他好文 > 详细

dfs模版

时间:2014-06-13 17:45:35      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:style   color   string   set   rgb   for   

dfs

#include <stdio.h>

#include <string.h>

char Map[16][16];

int mv[16][16];

//mv[i][j] == 0 没有被访问

//mv[i][j] == 1 已经被访问

struct N

{

    int x,y;

} ;

int jx[] = { 0,-1, 0, 1};

int jy[] = { 1, 0,-1, 0};

int Min;

void dfs(int x,int y,int n,int m,int ans)

{

    if(ans >= Min)

    {

        return ;

    }

   if(Map[x][y] == ‘Y‘)

    {       

       if(ans < Min)   

       {

            Min = ans;

        }

       return ;

    }

    N f;

    for(int i = 0; i < 4; ++i)

    {

        f.x = x + jx[i];

        f.y = y + jy[i];

        if(0 <= f.x && f.x < n && 0 <= f.y && f.y < m && mv[f.x][f.y] == 0 && Map[f.x][f.y] != ‘#‘)

        {

            mv[f.x][f.y] = 1;

            dfs(f.x,f.y,n,m,ans+1);

            mv[f.x][f.y] = 0;

        }

    }

}

int main()

{

    int n,m,i,j;

    while(scanf("%d %d",&n,&m) != EOF)

    {

        memset(mv,0,sizeof(mv));

        for(i = 0; i < n; ++i)

        {

            scanf("%*c%s",Map[i]);

        }

        for(i = 0; i < n; ++i)

        {

            for(j = 0; j < m; ++j)

            {

                if(Map[i][j] == ‘X‘)

                    break;

            }

            if(j != m)

                break;

        }

        Min = (1<<20);

        dfs(i,j,n,m,0);

        if(Min == (1<<20))

        {

            printf("-1\n");

        }

        else

        {

            printf("%d\n",Min);

        }

    }

    return 0;

}

dfs模版,布布扣,bubuko.com

dfs模版

标签:style   color   string   set   rgb   for   

原文地址:http://www.cnblogs.com/zhangmingcheng/p/3784549.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!