• POJ 1321 棋盘问题


    题目链接:https://cn.vjudge.net/problem/POJ-1321

    和八皇后问题不同:当k < n 时,某些行可以不必填

    思路:从当前行i的'#'开始搜,标记纵坐标,从i+1行到n-1行搜下一个‘#’(默认从第0行开始)

     1 #include <iostream>
     2 #include <cstring>
     3 #include <cstdio>
     4 #include <algorithm>
     5 #define mem(a,b) memset(a,b,sizeof(a));
     6 using namespace std;
     7 #define INF 0x3f3f3f3f
     8 typedef long long ll;
     9 const int maxn = 50005;
    10 int n,k,vis[10],ans;
    11 char s[10][10];
    12 void dfs(int r,int t) {
    13     if(t == k) {//当棋子总数为k时,停止搜索,返回上一层
    14         ans++;
    15         return ;
    16     }
    17     for(int i = r + 1; i < n; i++) {//从r+1行到n-1行搜下一个'#'
    18         for(int j = 0 ; j < n; j++) {
    19             if(s[i][j] == '#'&&!vis[j]){
    20                 vis[j] = 1;
    21                 dfs(i,t+1);
    22                 vis[j] = 0;
    23             }
    24         }
    25     }
    26 }
    27 int main()
    28 {
    29 
    30 
    31     while(cin >> n >> k) {
    32         ans = 0;
    33         if(n == -1 && k == -1)
    34             break;
    35         for(int i = 0; i < n; i++) {
    36             cin >> s[i];
    37         }
    38         for(int i = 0; i < n; i++) {
    39             for(int j = 0; j < n; j++) {
    40                 if(s[i][j] == '#') {
    41                     vis[j] = 1;// 标记纵坐标
    42                     dfs(i,1);
    43                     vis[j] = 0;
    44                 }
    45             }
    46         }
    47         cout << ans << endl;
    48     }
    49     return 0;
    50 }
  • 相关阅读:
    ZOJ 3954 Seven-Segment Display
    ZOJ 3955 Saddle Point
    ZOJ 3950 How Many Nines
    ZOJ 3957 Knuth-Morris-Pratt Algorithm
    PAT L2-018. 多项式A除以B
    hihocoder 1500 EL SUENO
    hihocoder 1498 Diligent Robots
    hihocoder 1497 Queen Attack
    hihocoder 1490 Tree Restoration
    SCU 4443 Range Query
  • 原文地址:https://www.cnblogs.com/LLLAIH/p/11352730.html
Copyright © 2020-2023  润新知