zoukankan      html  css  js  c++  java
  • Problem A POJ 1321 棋盘问题(dfs)

    A - 棋盘问题
    Time Limit:1000MS     Memory Limit:10000KB     64bit IO Format:%I64d & %I64u

    Description

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

    Input

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

    Output

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

    Sample Input

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

    Sample Output

    2
    1


    题目大意:
      就是说,给你一个n*n的棋盘和k个棋子,然后,你要做的就是在这个棋盘中放入k个棋子使得每个棋子不能出现在同一行和同一列上。
    解题思路:
      这么像八皇后问题,只不过这个棋盘并不是规则的棋盘,也就是说,'#'表示可以放入棋子,'.'表示不能放入棋子,那么只要求不能同行和同列,
    我们直接上dfs就好维护一个row[]和一个col[],每次回溯下,记住要用pos<n*n的特点来搞这个题,当n==pos的时候,我们就知道已经遍历完成
    整个棋盘了。

    代码:


     1 # include<cstdio>
     2 # include<iostream>
     3 # include<cstring>
     4 
     5 using namespace std;
     6 
     7 # define MAX 10
     8 
     9 int a[MAX][MAX];
    10 int row[MAX],col[MAX];
    11 char grid[MAX][MAX];
    12 int n,k;
    13 int ans;
    14 
    15 void dfs ( int pos ,int t )
    16 {
    17     if ( t==k )
    18     {
    19         ans++;
    20         return;
    21     }
    22     while ( pos < n*n )
    23     {
    24         int x = pos/n, y = pos%n;
    25         if ( row[x]==0&&col[y]==0&&a[x][y]==1 )
    26         {
    27             row[x] = col[y] = 1;
    28             dfs(pos+1,t+1);
    29             row[x] = col[y] = 0;
    30         }
    31         pos++;
    32     }
    33 }
    34 
    35 
    36 int main(void)
    37 {
    38     while ( scanf("%d%d",&n,&k)!=EOF )
    39     {
    40         if ( n==-1&&k==-1 )
    41             break;
    42         for ( int i = 0;i < n;i++ )
    43             scanf("%s",grid[i]);
    44         for ( int i = 0;i < n;i++ )
    45         {
    46             for ( int j = 0;j < n;j++ )
    47             {
    48                 if ( grid[i][j]=='#' )
    49                     a[i][j] = 1;
    50                 else
    51                     a[i][j] = 0;
    52             }
    53         }
    54         ans = 0;
    55         dfs(0,0);
    56         printf("%d
    ",ans);
    57         memset(row,0,sizeof(row));
    58         memset(col,0,sizeof(col));
    59     }
    60 
    61 
    62 
    63     return 0;
    64 }
  • 相关阅读:
    bfs入门 (HDU
    Codeforces Round #570 (Div. 3)B
    nyoj 277-车牌号 (map, pair, iterator)
    nyoj 276-比较字母大小 (顺序比较, 逆序输出)
    nyoj 275-队花的烦恼一 (stack, push, pop)
    nyoj 274-正三角形的外接圆面积 (R = PI * a * a / 3)
    nyoj 273-字母小游戏 (getline(cin, string))
    nyoj 268-荷兰国旗问题 (count)
    nyoj 266-字符串逆序输出 (isdigit(), geline(cin, my_string))
    nyoj 264-国王的魔镜 (string[-1:-int(str_len/2+1):-1])
  • 原文地址:https://www.cnblogs.com/wikioibai/p/4524136.html
Copyright © 2011-2022 走看看