N-Queens
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: bool place(vector<int> &board, int t){ for(int i = 0; i < t; i++){ if(abs(t - i) == abs(board[t] - board[i]) || board[t] == board[i]) return false; } return true; } void backTrace(vector<int> &board, int t, vector<string> &vs, vector<vector<string> > &vvs){ int n = board.size(); if(t >= n){ vvs.push_back(vs); return; } for(int i = 0; i < n; i++){ board[t] = i; string str(n, '.'); str[i] = 'Q'; vs.push_back(str); if(place(board, t)){ backTrace(board, t + 1,vs, vvs); } vs.pop_back(); } } vector<vector<string> > solveNQueens(int n) { vector<int> board(n, 0); vector<vector<string> > vvs; vector<string> vs; for(int i = 0; i < n; i++) board[i] = i; backTrace(board, 0, vs, vvs); return vvs; } };