Little Bishops

Little Bishops

Little Bishops A bishop is a piece used in the game of chess which can only move diagonally from its current position. Two bishops attack each other if one is on the path of the other. In the figure below, the dark squares represent the reachable locations for bishop B1 from its current position. Bishops B1 and B2 are in attacking position, while B1 and B3 are not. Bishops B2 and B3 are also in non-attacking position. Given two numbers n and k, determine the number of ways one can put k bishops on an n x n chessboard so that no two of them are in attacking positions.

The input file may contain multiple test cases. Each test case occupies a single line in the input file and contains two integers n(1 <= n <= 8) and k(0 <= k<=n2). A test case containing two zeros terminates the input

For each test case, print a line containing the total number of ways one can put the given number of bishops on a chessboard of the given size so that no two of them lie in attacking positions. You may safely assume that this number will be less than 1015.

8 6
4 4
0 0

5599888
260

#include<stdio.h>

struct Pos
{
int x;
int y;
};

class Xiang
{
public:
bool Place(int i,int x, int y);
void Bishops(int i, int s_x, int s_y, int n, int k);
int count;
Pos pstk;
};

bool Xiang::Place(int i,int x, int y)
{
for (int j = 1; j < i; ++j)
{
if ( (x - pstk[j].x) == (y - pstk[j].y) || (x - pstk[j].x) == -(y - pstk[j].y))
return false;
}
return true;
}

void Xiang::Bishops(int i, int s_x, int s_y, int n, int k)
{
for (int y = s_y + 1; y < n; ++y)
{
if (Place(i,s_x,y))
{
pstk[i].x = s_x;
pstk[i].y = y;

if (i == k)
++count;
else
Bishops(i+1, s_x, y, n, k);
}
}

for (int x = s_x+1; x < n; ++x)
{
for (int y = 0; y < n; ++y)
{
if (Place(i,x,y))
{
pstk[i].x = x;
pstk[i].y = y;

if (i == k)
++count;
else
Bishops(i+1, x, y, n, k);
}
}
}
}

int main()
{
int n, k;
while (scanf("%d%d",&n,&k), n!=0 && k!=0)
{
Xiang obj;
obj.count = 0;
obj.Bishops(1,0,-1,n,k);
printf("%d\n",obj.count);
}

return 0;
}

#include<stdio.h>

struct Pos
{
int x;
int y;
};

class Xiang
{
public:
bool Place(int i,int x, int y);
void Bishops(int i, int s_x, int s_y, int n, int k);
int count;
Pos pstk;
};

bool Xiang::Place(int i,int x, int y)
{
for (int j = 1; j < i; ++j)
{
if ( (x - pstk[j].x) == (y - pstk[j].y) || (x - pstk[j].x) == -(y - pstk[j].y))
return false;
}
return true;
}

void Xiang::Bishops(int i, int s_x, int s_y, int n, int k)
{
for (int y = s_y + 1; y < n; ++y)
{
if (Place(i,s_x,y))
{
pstk[i].x = s_x;
pstk[i].y = y;

if (i == k)
++count;
else
Bishops(i+1, s_x, y, n, k);
}
}

for (int x = s_x+1; x < n; ++x)
{
for (int y = 0; y < n; ++y)
{
if (Place(i,x,y))
{
pstk[i].x = x;
pstk[i].y = y;

if (i == k)
++count;
else
Bishops(i+1, x, y, n, k);
}
}
}
}

int main()
{
int n, k;
while (scanf("%d%d",&n,&k), n!=0 && k!=0)
{
Xiang obj;
obj.count = 0;
obj.Bishops(1,0,-1,n,k);
printf("%d\n",obj.count);
}

return 0;
}