深搜_方向搜索(HDU_1035)

需要注意特殊案例的是:最后走到入口出时,步数为 0 。

#include <stdio.h>
#include <string.h>

#define M 12

char move_map[4] = {'N','S','E','W'};
int  move_do[4][2] = {-1,0,1,0,0,1,0,-1};
char map[M][M];
int step[M][M];
int row,col,in,re_step,re_round;

int jud(int r, int c)
{
    if(r<0 || r>row-1 || c<0 || c>col-1)    return 0;
    return 1;
}

void dfs(int r, int c,int s)
{
    for(int i=0; i<4; i++)
    {
        if(map[r][c] == move_map[i])
        {
            int __r = r + move_do[i][0];
            int __c = c + move_do[i][1];

            if(step[__r][__c] > 0)
            {
                re_step = step[__r][__c] - 1;
                re_round = s - step[__r][__c] + 1;
                return ;
            }
            if(!jud(__r,__c))
            {
                re_step = step[r][c];
                return ;
            }
            step[__r][__c] = step[r][c] + 1;
            dfs(__r, __c, s + 1);
        }
    }
}

int main()
{
//    freopen("in.txt","r",stdin);
    
    while(scanf("%d%d%d",&row,&col,&in) && row+col+in)
    {
        for(int i=0; i<row; i++)
        {
            scanf("%s",map[i]);
        }
        memset(step,-1,sizeof(step));
        re_step = re_round = 0;
        step[0][in-1] = 1;
        dfs(0,in-1,1);
        if(re_round)
        {
            printf("%d step(s) before a loop of %d step(s)\n",re_step,re_round);
        }
        else
        {
            printf("%d step(s) to exit\n",re_step);
        }
    }
    return 0;
}

 

posted on 2013-08-11 19:31  lk1993  阅读(175)  评论(0编辑  收藏  举报