在看Scala视频时,有个例子说是用Scala写八皇后,我突然想我现在能不能马上写出八皇后呢?
于是打开IDE开始练习
共计20分钟不到
其中有十分钟是在写如何判断某一点上能否放一个皇后(横竖斜)
这个速度还算是可以
#include <stdio.h>
#include <stdlib.h>
#include "string"
#include "iostream"
#include "fstream"
#include "string.h"
#include "assert.h"
#include <time.h>
#include "algorithm"
#include "vector"
#define N 8
using namespace std;
int chessboard[N][N];
int qCount = 0;
void init()
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
chessboard[i][j] = 0;
}
}
}
void set(int x, int y)
{
chessboard[x][y] = 1;
}
void unset(int x, int y)
{
chessboard[x][y] = 0;
}
// whether queen can set in this position
bool testQ(int x, int y)
{
for (int i = 0; i < N; i++)
{
if (chessboard[i][y] == 1)
{
return false;
}
}
for (int i = 0; i < N; i++)
{
if (chessboard[x][i] == 1)
{
return false;
}
}
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (abs(i - x) == abs(j - y) && chessboard[i][j] == 1)
return false;
}
}
return true;
}
void printChessboard()
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
printf("%d ", chessboard[i][j]);
}
printf("\n");
}
printf("\n");
}
void queen(int nowRow)
{
for (int i = 0; i < N; i++)
{
if (testQ(nowRow, i) == true)
{
set(nowRow, i);
if (nowRow == N - 1)
{
printChessboard();
qCount++;
}
else
{
queen(nowRow + 1);
}
unset(nowRow, i);
}
}
}
int main()
{
init();
queen(0);
printf("%d Queen has %d solution\n", N, qCount);
return 0;
}