• 搜索复习


    POJ 1321 棋盘问题

    Time Limit: 1000MS Memory Limit: 10000K
    Total Submissions: 110901 Accepted: 50143

    Description

    在一个给定形状的棋盘(形状可能是不规则的)上面摆放棋子,棋子没有区别。要求摆放时任意的两个棋子不能放在棋盘中的同一行或者同一列,请编程求解对于给定形状和大小的棋盘,摆放k个棋子的所有可行的摆放方案C。

    Input

    输入含有多组测试数据。
    每组数据的第一行是两个正整数,n k,用一个空格隔开,表示了将在一个n*n的矩阵内描述棋盘,以及摆放棋子的数目。 n <= 8 , k <= n
    当为-1 -1时表示输入结束。
    随后的n行描述了棋盘的形状:每行有n个字符,其中 # 表示棋盘区域, . 表示空白区域(数据保证不出现多余的空白行或者空白列)。

    Output

    对于每一组数据,给出一行输出,输出摆放的方案数目C (数据保证C<2^31)。

    Sample Input

    #.
    .#
    4 4
    ...#
    ..#.
    .#..
    #...
    -1 -1
    

    记录:搜索(dfs)复习

    搜索时注意遍历顺序,状态设计和边界条件

    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    #include <cstring>
    #include <set>
    typedef long long ll;
    using namespace std;
    
    template <typename T>void in(T &x) {
        x = 0; T f = 1; char ch = getchar();
        while(!isdigit(ch)) {if(ch == '-') f = -1; ch = getchar();}
        while(isdigit(ch)) {x = 10*x + ch - '0'; ch = getchar();}
        x *= f;
    }
    
    template <typename T>void out(T x) {
        if(x < 0) putchar('-'),x = -x;
        if(x > 9) out(x/10);
        putchar(x%10+'0');
    }
    
    //---------------------------------------------------------------
    
    int n,k,ans;
    int vis[10];
    char a[10][10];
    
    void dfs(int x,int cnt) {//当前是第x行,已放了cnt个棋子 
        if(cnt == k) {
            ans++; return;
        }
        for(int j = 1;j <= n; j++) {
            if(vis[j] == 0 && a[x][j] == '#') {
            	vis[j] = 1;
            	dfs(x+1,cnt+1);
            	vis[j] = 0;
    		}
        }//当前行放
    	if(x < n) dfs(x+1,cnt);//直接到下一行,当前行不放 //debug add if(x < n) : 有下一行才能到下一行 
    }
    
    int main() {
    	//freopen("input.txt","r",stdin);
        while(1) {
            ans = 0;
            cin >> n >> k;
            if(n == -1 && k == -1) break;
            for(int i = 1;i <= n; i++) {
                for(int j = 1;j <= n; j++) {
                    cin >> a[i][j];
                }
            }
            dfs(1,0);
            out(ans);putchar('
    ');
        }
        return 0;
    }
    
  • 相关阅读:
    ZigBee学习二 LED点对点通信
    ZigBee学习一 任务处理函数_ProcessEvent
    关于count(分组字段)的问题
    hive命令行 显示字段名配置
    Linux 查看当前目录下的文件大小
    apache 端口号与 CDH端口号对比
    dbeaver驱动问题解决方案
    【数学】递推算法之平面分割问题总结
    【HDOJ】(1426)Sudoku Killer (dfs)
    【牛客】牛客小白月赛1(数学)
  • 原文地址:https://www.cnblogs.com/mzg1805/p/15000911.html
Copyright © 2020-2023  润新知