首页 > 代码库 > POJ 1315 Don't Get Rooked(dfs)

POJ 1315 Don't Get Rooked(dfs)

A - Don‘t Get Rooked
Time Limit:1000MS     Memory Limit:10000KB     64bit IO Format:%I64d & %I64u
Submit Status Practice POJ 1315

Description

In chess, the rook is a piece that can move any number of squares vertically or horizontally. In this problem we will consider small chess boards (at most 4x4) that can also contain walls through which rooks cannot move. The goal is to place as many rooks on a board as possible so that no two can capture each other. A configuration of rooks is legal provided that no two rooks are on the same horizontal row or vertical column unless there is at least one wall separating them. 

The following image shows five pictures of the same board. The first picture is the empty board, the second and third pictures show legal configurations, and the fourth and fifth pictures show illegal configurations. For this board, the maximum number of rooks in a legal configuration is 5; the second picture shows one way to do it, but there are several other ways. 

Your task is to write a program that, given a description of a board, calculates the maximum number of rooks that can be placed on the board in a legal configuration. 

Input

The input contains one or more board descriptions, followed by a line containing the number 0 that signals the end of the file. Each board description begins with a line containing a positive integer n that is the size of the board; n will be at most 4. The next n lines each describe one row of the board, with a ‘.‘ indicating an open space and an uppercase ‘X‘ indicating a wall. There are no spaces in the input.

Output

For each test case, output one line containing the maximum number of rooks that can be placed on the board in a legal configuration.

Sample Input

4.X......XX......2XX.X3.X.X.X.X.3....XX.XX4................0

Sample Output

51524


n皇后的改编题 由于n比较小可以直接dfs

#include<cstdio>#include<iostream>#include<algorithm>using namespace std;char mat[10][10];int ans,n;bool ok(int x,int y){    int i;    if(mat[x][y]!=‘.‘) return false;    for(i=x+1;i<=n&&mat[i][y]!=‘X‘;i++)    {        if(mat[i][y]==‘0‘) return false;    }    for(i=x-1;i>=1&&mat[i][y]!=‘X‘;i--)    {        if(mat[i][y]==‘0‘) return false;    }    for(i=y;i<=n&&mat[x][i]!=‘X‘;i++)    {        if(mat[x][i]==‘0‘) return false;    }    for(i=y-1;i>=1&&mat[x][i]!=‘X‘;i--)    {        if(mat[x][i]==‘0‘) return false;    }    return true;}void dfs(int coun){    int i,j;    for(i=1;i<=n;i++)    {        for(j=1;j<=n;j++)        {            if(ok(i,j))            {                mat[i][j]=‘0‘;                dfs(coun+1);                mat[i][j]=‘.‘;            }        }    }    if(ans<coun) ans=coun;}int main(){    int i,j;    while(cin>>n&&n!=0)    {        gets(mat[0]);//吸收换行        for(i=1;i<=n;i++)        {            gets(mat[i]+1);        }        ans=0;        dfs(0);        printf("%d\n",ans);    }    return 0;}

  




POJ 1315 Don't Get Rooked(dfs)