Leetcode-n-queens

Source: Internet
Author: User

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 {PRIVATE: STD: vector <STD: String> res; public: STD: vector <STD :: string> solvenqueens (int n) {STD: vector <STD: String> cur (n, STD: string (n ,'. '); DFS (cur, 0); Return res;} void DFS (STD: vector <STD: String> & cur, int row) {If (ROW = cur. size () {res. push_back (cur); return;} For (INT Col = 0; Col <cur. size (); Col ++) if (isvalid (cur, row, col) {cur [row] [Col] = 'q'; DFS (cur, row + 1); cur [row] [col] = '. ';}} // determines whether the Queen is placed in the cur [row] [col] location. Bool isvalid (STD: vector <STD: String> & cur, int row, int col) {// column for (INT I = 0; I <row; I ++) if (cur [I] [col] = 'q') return false; // right diagonal line for (INT I = row-1, j = col-1; I >=0 & J> = 0; I --, j --) if (cur [I] [J] = 'q ') return false; // left diagonal line for (INT I = row-1, j = Col + 1; I >=0 & J <cur. size (); I --, J ++) if (cur [I] [J] = 'q') return false; return true ;}};


Leetcode-n-queens

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.