UVa 11214 - Guarding the Chessboard

来源:互联网 发布:mac双系统卸载win7 编辑:程序博客网 时间:2024/04/30 03:04

这是一道迭代加深搜索的水题,与八皇后问题的解决方法一样,用一个数组来储存行列对角线副对角线是否有棋子,用迭代加深搜索来完成。


        //stand c++
#include<iostream>
#include<algorithm>
#include<vector>
#include<set>
//#pragma comment(linker, "/STACK:102400000,102400000")
        //stand c
#include<cstdio>
#include <cstring>
using namespace std;


int n, m;


bool vis[4][30];
char web[15][15];


bool allcapture(){
    for(int i = 0; i < n; ++i)
    for(int j = 0; j < m; ++j){
        if(web[i][j] == 'X' && !vis[0][i] && !vis[1][j] && !vis[2][i+j] && !vis[3][n+j-i])
            return false;
    }
    return true;
}


bool dfs(int lstp, int cur){
    if(lstp == 0){
        if(allcapture())
            return true;
        return false;
    }
    for(int i = cur; i < n*m; ++i){
        int x = i / m, y = i % m;
        int t0 = vis[0][x], t1 = vis[1][y], t2 = vis[2][x+y], t3 = vis[3][n+y-x];
        vis[0][x] = vis[1][y] = vis[2][x+y] = vis[3][n+y-x] = true;
        if(dfs(lstp-1, i+1))return true;
        vis[0][x] = t0, vis[1][y] = t1, vis[2][x+y] = t2, vis[3][n+y-x] = t3;
    }
    return false;
}


int main(){
    int cs = 0;
    while(~scanf("%d", &n) && n){
        printf("Case %d: ", ++cs);
        scanf("%d", &m);
        for(int i = 0; i < n; ++i)
            scanf("%s", web[i]);
        int ans = 0;
        for(int i = 1; i <= 10; ++i){
            memset(vis, 0, sizeof(vis));
            if(dfs(i, 0)){ans = i; break;}
        }
        printf("%d\n", ans);
    }
    return 0;
}

0 0