【N-Queens】cpp

题目:

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:
        static vector<vector<string> > solveNQueens(int n)
        {
            vector<vector<string> > ret;
            if ( n==0 ) return ret;
            vector<string> tmp;
            vector<bool> colUsed(n,false);
            vector<bool> diagUsed1(2*n-1,false);
            vector<bool> diagUsed2(2*n-1,false);
            Solution::dfs(ret, tmp, n, colUsed, diagUsed1, diagUsed2);
            return ret;
        }
        static void dfs(
            vector<vector<string> >& ret,
            vector<string>& tmp,
            int n,
            vector<bool>& colUsed,
            vector<bool>& diagUsed1,
            vector<bool>& diagUsed2 )
        {
            const int row = tmp.size();
            if ( row==n )
            {
                ret.push_back(tmp);
                return;
            }
            string curr(n,‘.‘);
            for ( size_t col = 0; col<n; ++col )
            {
                if ( !colUsed[col] && !diagUsed1[col+n-1-row] && !diagUsed2[col+row] )
                {
                    colUsed[col] = !colUsed[col];
                    diagUsed1[col+n-1-row] = !diagUsed1[col+n-1-row];
                    diagUsed2[col+row] = !diagUsed2[col+row];
                    curr[col] = ‘Q‘;
                    tmp.push_back(curr);
                    Solution::dfs(ret, tmp, n, colUsed, diagUsed1, diagUsed2);
                    tmp.pop_back();
                    curr[col] = ‘.‘;
                    diagUsed2[col+row] = !diagUsed2[col+row];
                    diagUsed1[col+n-1-row] = !diagUsed1[col+n-1-row];
                    colUsed[col] = !colUsed[col];
                }
            }
        }
};

tips:

深搜写法:

1. 找到一个解的条件是tmp的长度等于n

2. 在一列中遍历每个位置,是否能够放置Q,并继续dfs;返回结果后,回溯tmp之前的状态,继续dfs。

一开始遗漏了对角线也不能在有超过一个Q的条件,补上之后就AC了。

时间: 2024-10-11 10:28:55

【N-Queens】cpp的相关文章

【Word Break】cpp

题目: Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, givens = "leetcode",dict = ["leet", "code"]. Return true becau

【Sudoku Solver】cpp

题目: Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character '.'. You may assume that there will be only one unique solution. A sudoku puzzle... ...and its solution numbers marked in red. 代码: cla

【Subsets II】cpp

题目: Given a collection of integers that might contain duplicates, nums, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example,If nums = [1,2,2], a sol

【LRU Cache】cpp

题目: Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.

【Rotate List】cpp

题目: Given a list, rotate the list to the right by k places, where k is non-negative. For example:Given 1->2->3->4->5->NULL and k = 2,return 4->5->1->2->3->NULL. 代码: /** * Definition for singly-linked list. * struct ListNode {

【Text Justification】cpp

题目: Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pa

【Simplify Path】cpp

题目: Given an absolute path for a file (Unix-style), simplify it. For example,path = "/home/", => "/home"path = "/a/./b/../../c/", => "/c" click to show corner cases. Corner Cases: Did you consider the case whe

【Implement strStr() 】cpp

题目: Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Update (2014-11-02):The signature of the function had been updated to return the index instead of the pointer. If you st

【Valid Palindrome】cpp

题目: Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example,"A man, a plan, a canal: Panama" is a palindrome."race a car" is not a palindrome. Note:Have you consider tha

【Jump Game】cpp

题目: Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. For example: