The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens‘ placement, where ‘Q‘
and ‘.‘
both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]
Subscribe to see which companies asked this question
主要参考 http://blog.csdn.net/hackbuteer1/article/details/6657109
class Solution { public: vector<vector<string>> solveNQueens(int n) { int i; //初始化 for (i=0; i<n*n; i++) { _queue_arr[i] = INIT_VAL; } vector<vector<string>> res; int row = 0; int col = 0; //遍历每一行 while (row < n) { //遍历每一列 while (col < n) { //如果冲突,就计算下一列 if (is_conflict(row, col, n)) { col++; } else { _queue_arr[row] = col; col = 0; break; } } //遍历完每一列后,检查是否成功放置皇后 //如果失败 if (col == n) { //如果当前行是第0行了,就说明所有的jie都被求出了 if (0 == row) { break; } else { //如果不是,就从上一行的下一列开始放置皇后,并进行判断 row--; col = _queue_arr[row]; col++; _queue_arr[row] = INIT_VAL; continue; } //如果当前行是最后一行了,就输出 } else if (row == n - 1) { handle_result(res, n); col = _queue_arr[row] + 1; _queue_arr[row] = INIT_VAL; continue; //不是最后一行,就计算下一行 } else { row++; }; } return res; } private: /* * 判断是否冲突,主要检测方式是 ,如果冲突 * queue_arr[i] == queue_arr[j] * |queue_arr[i] - queue_arr[j]| = |i - j| * * @param row: 当前行 * @param col: 当前列 * @param n: 所有的行数和列数 */ bool is_conflict(int row, int col, int n) const{ int i; for (i=0; i<n; i++) { if (_queue_arr[i] == col || abs(_queue_arr[i] - col) == abs(i - row)) { return true; } } return false; } /* * 处理结果 * @param res_str 结果集合 * @param n 行数 */ void handle_result(vector<vector<string>> &res_str, int n) { vector<string> slu_str; int i,j; for (i=0; i<n; i++) { string tmp = ""; for (j=0; j<n; j++) { if (_queue_arr[i] == j) { tmp += "Q"; } else { tmp += "."; } } slu_str.push_back(tmp); } res_str.push_back(slu_str); } private: int _queue_arr[1000]; const static int INIT_VAL = -10000; };
时间: 2024-10-11 14:36:47