leetcode 050 —— N-Queens

来源:互联网 发布:定海神针网络上啥意思 编辑:程序博客网 时间:2024/05/16 12:57

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.."]]

直接上代码

class Solution {public:vector<vector<string> > solveNQueens(int n) {//string s( n, '.' );vector<string> path(n, string (n, '.'));vector<vector<string> > res;create(0, n, path, res);return res;}bool isValid(int v, int s, int n, vector<string> &path){   //第v行的第s列 是否有效int vv, ss;for (int i = 0; i < v; i++){vv = i;ss = path[vv].find('Q');if (ss == s)return false;if ((v - vv) == (s - ss))return false;if ((v - vv) == (ss - s))return false;}return true;}void create(int level, int n, vector<string> &path, vector<vector<string> > &res){if (level == n){res.push_back(path);return;}for (int i = 0; i < n; i++){if (isValid(level, i, n, path)){path[level][i] = 'Q';create(level + 1, n, path, res);path[level][i] = '.';}}}};


0 0
原创粉丝点击