默写八皇后

来源:互联网 发布:张萱妍让网络封了 编辑:程序博客网 时间:2024/04/27 15:43

在看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 8using 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 positionbool 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;}


0 0