天天写算法之(DFS)The Worm Turns

地址: 点击打开链接
这个题目是真的-。-。里面还有个大bug。直接做就可以了。

其中如果你把
int dir[4][2] = {{0,1},{-1,0},{1,0},{0,-1}};

换成
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};


下面对应也改了,那么恭喜你,你就错了!woc这tm什么玩意,写这个代码用了十分钟,找这个bug用了一个多小时????最后还是黑人问号???
正确代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string.h>
#define MAX 650
using namespace std ;
int m , n ,num_blocks, sx,sy,sd,block_x,block_y ;
int res_x,res_y,res_dir,res_max;
int Map[MAX][MAX];
int Vis[MAX][MAX];
int dir[4][2] = {{0,1},{-1,0},{1,0},{0,-1}}; 
char char_dir ;
void dfs(int x , int y , int d ,int step)
{
    if(step>res_max)
    {
        res_x = sx;
        res_y = sy;
        res_dir = sd;
        res_max = step;
    }
    int tx =x+dir[d][0];
    int ty =y+dir[d][1];

   if(tx>=0&&tx<m&&ty>=0&&ty<n&&Map[tx][ty]!=1&&Vis[tx][ty]==0)
    {
        Vis[tx][ty]=1;
        dfs(tx,ty,d,step+1);
        Vis[tx][ty]=0;
    }else {
        if(step==0) return ;
        for(int k = 0 ; k <4 ; k ++)
        {
            if(k==d)
                continue ;
            tx = x+dir[k][0];
            ty = y+dir[k][1];
            if(tx>=0&&tx<m&&ty>=0&&ty<n&&Map[tx][ty]!=1&&Vis[tx][ty]==0)
            {
                Vis[tx][ty]=1;
                dfs(tx,ty,k,step+1);
                Vis[tx][ty]=0;
            }
        }

    }

}

int main(){
    int i , j ,index = 1;
    while(~scanf("%d%d",&m,&n)&&m+n)
    {
        memset(Vis,0,sizeof(Vis));
        memset(Map,0,sizeof(Map));
        scanf("%d",&num_blocks);
        while(num_blocks--)
        {
            scanf("%d%d",&block_x,&block_y);
            Map[block_x][block_y] = 1 ;
            Vis[block_x][block_y] = 1 ;
        }
        res_max = 0 ;
        for(i = 0 ; i <m ; i ++)
        {
            for(j = 0 ; j <n ; j ++)
            {
                if(Map[i][j])
                    continue ;
                    Vis[i][j] = 1 ;
                    sx = i ; sy=j ;
                    for(int k = 0 ; k <4 ; k ++)
                    {
                      
                            sd = k ;
                            dfs(i,j,k,0);
                    }
                     Vis[i][j] = 0 ;
            }
        }
        if(res_dir==0)
            char_dir = 'E';
        else if(res_dir==1)
            char_dir = 'N';
        else if(res_dir==2)
            char_dir = 'S';
        else if(res_dir==3)
            char_dir = 'W';
        printf("Case %d: %d %d %d %c\n",index++,res_max+1,res_x,res_y,char_dir);
    }
    return 0 ;
}


猜你喜欢

转载自blog.csdn.net/qq_36616268/article/details/80542549