zoukankan      html  css  js  c++  java
  • Poj(2488),按照字典序深搜

    题目链接:http://poj.org/problem?id=2488

    思路:按照一定的字典序深搜,当时我的想法是把所有的可行的路径都找出来,然后字典序排序。

    后来,凡哥说可以在搜索路径的时候就按照字典序搜索,这样一找到可行的路径就输出来就行了。这里我吸取了之前八皇后问题时犯的错,并且优化了一下写法,就是flag,这是参考了jhf大神的写法了。

    但是jhf大神的写法,思路和我一样,但是他的x,y坐标还要转来转去,我就没有这么写了,还是按照我的代码风格好一些。

    #include <stdio.h>
    #include <string.h>
    
    bool vis[30][30];
    int to[8][2] = {{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}};
    int R,C;
    bool flag;
    
    struct Path
    {
        int r;
        int c;
    } path[30*30];
    
    bool judge(int r,int c)
    {
        if(r<0||r>=R||c<0||c>=C||vis[r][c])
            return false;
        return true;
    }
    
    void dfs(int r,int c,int k)
    {
        path[k].c = c;
        path[k].r = r;
    
        if(k==C*R)
        {
            flag = true;
            return ;
        }
        for(int i=0; i<8; i++)
        {
            int rx = r+to[i][0];
            int cx = c+to[i][1];
            if(judge(rx,cx))
            {
                vis[rx][cx] = true;
                dfs(rx,cx,k+1);
                if(flag)
                    return;
                vis[rx][cx] = false;
            }
        }
    }
    
    int main()
    {
        int t;
        scanf("%d",&t);
        for(int cases=1; cases<=t; cases++)
        {
            memset(vis,false,sizeof(vis));
    
            printf("Scenario #%d:
    ",cases);
            scanf("%d%d",&R,&C);
            for(int i=0; i<C; i++)
            {
                for(int j=0; j<R; j++)
                {
                    flag = false;
                    vis[j][i] = true;
                    dfs(j,i,1);
                    if(flag)
                        break;
                    vis[j][i] = false;
                }
                if(flag)
                    break;
            }
            if(flag)
            {
                for(int i=1;i<=R*C;i++)
                    printf("%c%d",path[i].c+'A',path[i].r+1);
                puts("
    ");
            }
            else printf("impossible
    
    ");
        }
        return 0;
    }
  • 相关阅读:
    [leetcode-91-Decode Ways]
    [leetcode-72-Edit Distance]
    [leetcode-67-Add Binary]
    [leetcode-137-Single Number II]
    [leetcode-60-Permutation Sequence]
    [leetcode-55-Jump Game]
    [leetcode-18-4Sum]
    [leetcode-15-3Sum]
    [leetcode-47-Permutations II]
    easyui tabs update 强制刷新页面
  • 原文地址:https://www.cnblogs.com/TreeDream/p/5725987.html
Copyright © 2011-2022 走看看