POJ1321 棋盘问题(dfs)

题目链接

分析:

用 dfs 一行一行的搜索,col记录当前列是否已经放置。

 

AC代码如下:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
#include <cstring>
#include <queue>

using namespace std;

const int maxn = 10;

int n, k, cnt;
bool col[maxn];
char G[maxn][maxn];

void dfs(int row, int num) {
    if(num == k) { cnt++; return ; }

    if(row+1 > n) return;

    for(int j=0; j<n; j++) {
        if(G[row][j] == '#') {
            if(!col[j]) {
                col[j] = true;
                dfs(row+1, num+1);
                col[j] = false;
            }
        }
    }

    dfs(row+1, num);
}

int main() {

    while(scanf("%d%d", &n, &k) == 2) {
      if(n == -1 && k == -1) break;

      memset(col, false, sizeof(col));

      for(int i=0; i<n; i++) {
          scanf("%s", G[i]);
      }

      cnt = 0;

      dfs(0, 0);

      printf("%d\n", cnt);
    }

    return 0;
}

 

 

posted on 2013-07-31 15:50  Still_Raining  阅读(196)  评论(0编辑  收藏  举报