#include<iostream>
#include<vector>
#include<cstdlib>
using namespace std;
bool chess[8][8] =
{
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
};
bool conflict(const int& row, const int& col)
{
if (row == 0)
return false;
vector<int> ColPos;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < 8; j++)
{
if (chess[i][j] == true)
{
ColPos.push_back(j);
break;
}
}
}
for (int i = 0; i < row; i++)
{
if (col == ColPos[i])
return true;
}
for (int i = 0; i < row; i++)
{
int Row_dif = row - i;
int Col_dif = ColPos[i] - col;
if (Row_dif == Col_dif)
return true;
if (Row_dif == -Col_dif)
return true;
}
return false;
}
void Queen(void)
{
int seed = 1;
srand(seed);
loop:
for (int i = 0; i < 8; i++)
{
int pos = rand() % 8;
int n = 1;
while (conflict(i, pos) && n < 100)
{
pos = rand() % 8;
n++;
}
if (n >= 100)
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
chess[i][j] = false;
}
}
seed++;
goto loop;
}
chess[i][pos] = true;
}
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
cout << chess[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
int main(void)
{
Queen();
return 0;
}
|