zoukankan      html  css  js  c++  java
  • 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;
    }

    /**/

  • 相关阅读:
    tp5.1批量删除商品
    tp5.1 无限极分类前台展示
    jquery实现商品sku多属性选择(商品详情页)
    简单的权限管理php
    js的常用场景效果
    jquery 常用选择器基础语法学习
    js 注意事项使用误区
    js (单个的)点击式下拉菜单
    React中setState学习总结
    JavaScript面试核心考点(精华)
  • 原文地址:https://www.cnblogs.com/JMDWQ/p/2599899.html
Copyright © 2011-2022 走看看