Description
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
Output
Sample Input
4 .X.. .... XX.. .... 2 XX .X 3 .X. X.X .X. 3 ... .XX .XX 4 .... .... .... .... 0
Sample Output
5 1 5 2 4
#include<iostream>
#include<cstring>
using namespace std;
char board[5][5];
int visited[5][5];//visited数组表示此位置是否被访问过
int cnt,n,maxn;
bool place(int x,int y)
{
for(int i=x+1;i<n&&board[i][y]!='X';i++)
{
if(visited[i][y])
return false;
}
for(int i=x-1;i>=0&&board[i][y]!='X';i--)
{
if(visited[i][y])
return false;
}
for(int i=y+1;i<n&&board[x][i]!='X';i++)
{
if(visited[x][i])
return false;
}
for(int i=y-1;i>=0&&board[x][i]!='X';i--)
{
if(visited[x][i])
return false;
}
return true;
}
void placed(int cnt)
{
if(cnt>=maxn) maxn=cnt;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(!visited[i][j]&&board[i][j]=='.'&&place(i,j))
{
visited[i][j]=1;
placed(cnt+1);
visited[i][j]=0;
}
}
}
}
int main()
{
while(cin>>n&&n)
{
maxn=0;
memset(visited, 0, sizeof(visited));
memset(board, 0, sizeof(board));
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>board[i][j];
}
}
placed(0);
cout<<maxn<<endl;
}
return 0;
}
memset()函数原型是extern void *memset(void *buffer, int c, int count)
buffer:为指针或是数组 , c:是赋给buffer的值 , count:是buffer的长度.
这个函数在多用于清空数组.如:原型是memset(buffer, 0, sizeof(buffer))
memset 用来对一段内存空间全部设置为某个字符,一般用在对定义的字符串进行初始化为‘ ’或‘/0’;
例:char a[100];memset(a, '/0', sizeof(a));
memset可以方便的清空一个结构类型的变量或数组。
如:
struct sample_struct
{
char csName[16];
int iSeq;
int iType;
};
对于变量:
struct sample_strcut stTest;
一般情况下,清空stTest的方法:
stTest.csName[0]='/0';
stTest.iSeq=0;
stTest.iType=0;
用memset就非常方便:
memset(&stTest,0,sizeof(struct sample_struct));
如果是数组:
struct sample_struct TEST[10];
则
memset(TEST,0,sizeof(struct sample_struct)*10);