• DFS专题 Fire Net


    这道题暴力秒过,以前在ZOJ上见过,当时不会,还以为不剪枝铁定超呢,结果纯暴力就过了。

    # include <cstdio>
    # include <cstring>
    
    # define N 4 + 3
    
    int n, ans;
    char g[N][N];
    
    bool check(int x, int y)
    {
        int i = x;
        if (g[x][y] != '.') return false;
        while (i <= n)
        {
            if (g[i][y] == 'X') break;
            else if (g[i][y] == (i-1)*n+y) return false;
            else ++i;
        }
        i = x-1;
        while (i >= 1)
        {
            if (g[i][y] == 'X') break;
            else if (g[i][y] == (i-1)*n+y) return false;
            else --i;
        }
        i = y;
        while (i <= n)
        {
            if (g[x][i] == 'X') break;
            else if (g[x][i] == (x-1)*n+i) return false;
            else ++i;
        }
        i = y-1;
        while (i >= 1)
        {
            if (g[x][i] == 'X') break;
            else if (g[x][i] == (x-1)*n+i) return false;
            else --i;
        }
        return true;
    }
    
    void dfs(int x, int y, int cnt)
    {
        int i = 1, j = 1;
        //int tmp = (x-1)*n + y + 1, i = (tmp-1)/n+1, j = (tmp-1)%n+1;  // 错误的剪枝,没有通过样例
        //if (tmp == n*n) ans = (cnt > ans ? cnt : ans);
        if (cnt > ans) ans = cnt;
        for ( i = 1; i <= n; ++i)
        for ( j = 1; j <= n; ++j)
        {
            if (check(i,j))
            {
                g[i][j] = (i-1)*n+j;
                dfs(i, j, cnt+1);
                g[i][j] = '.';
            }
        }
    
    }
    
    void init(void)
    {
        for (int i = 1; i <= n; ++i)
            scanf("%s", g[i]+1);
    }
    
    void solve(void)
    {
        ans = 0;
    
        for (int i = 1; i <= n; ++i)
        for (int j = 1; j <= n; ++j)
        {
            if (g[i][j]=='.')
            {
                g[i][j] = (i-1)*n+j;
                dfs(i, j, 1);
                g[i][j] = '.';
            }
        }
    
        printf("%d\n", ans);
    }
    
    int main()
    {
        while (scanf("%d", &n), n)
        {
            init();
            solve();
        }
    
        return 0;
    }

    /**/

  • 相关阅读:
    APUE_1.7ErrorHandling Figure1.8Demonstrate strerror and perror
    4-7 使用tf.train.slice_input_producer读取列表样本
    Ubuntu16.4+github+pycharm
    4-5 Cifar10数据集解析
    4-6 TF之TFRecord数据打包案例
    matlab如何创建一个视频预览
    Alpha
    如何使用 declare-styleable
    LayoutParams使用
    桌面快捷方式的问题-创建-删除-判断
  • 原文地址:https://www.cnblogs.com/JMDWQ/p/2599899.html
Copyright © 2020-2023  润新知