Skip to main content

Backtracking - Question 1

Leetcode 51. N-Queens

The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.

Constraints:

1 <= n <= 9


Analysis:

For each row, we can only put one queen, so we can make the trial row by row.

For each row, every position is possible to place the queen. Once the queen is set, the position should be recorded, since this information has limitations on new queen's position.

To simply the record and also the check, we can use a one dimensional array for this: the index is for the row, and its value for the column. Both information determines the position of the queen placed.

Once reached the last row, we can check how many queens have been placed. 

If it equals to n, it means that we find a valid solution; 

If not, we need to go back the trial step, reset the trial, and make a second trial, ... until make and finish all the trials.


See the code below:


class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        m = n;
        ps.resize(m);
        fill(ps.begin(), ps.end(), -1);
        bt(0, 0);// row number, queen counts
        return res;
    }
private:
    int m;
    vector<vector<string>> res;
    vector<string> one;
    vector<int> ps;
    void bt(int x, int ct) {
        if(x==m) {
            if(ct==m) res.push_back(one);
            return;
        }
        string s(m, '.');
        for(int i=0; i<m; ++i) {
            // if(ps[x] != -1) continue;
            s[i] = 'Q';// make trial
            if(isValid(x, i)) {
                ps[x] = i;//record
                one.push_back(s);//save
                bt(x+1, ct+1);
                one.pop_back();//step back
                ps[x] = -1;//step back
            }
            s[i] = '.';// reset
        }
    }
    bool isValid(int x, int y) {
        for(int i=0; i<m; ++i) {
            if(i == x || ps[i] == -1) continue;
            if(y == ps[i] || abs(x-i) == abs(y-ps[i])) return false;
        }
        return true;
    }
};

 

Upper Layer

Comments

Popular posts from this blog

Bit Manipulation - Medium Level

 Leetcode 416 Partition Equal Subset Sum Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. Constraints: 1 <= nums.length <= 200 1 <= nums[i] <= 100 Analysis: There are different ways to solve this problem, such as dp with a time complexity of O(N^2). Since N is small to this question, so it is Okay to pass OJ. Besides the small N, the value of each element is also very small. So this gives us some chance to use "space to trad off time". The data structure to be used is bitset. For bitset, each bit can be either 0 or 1. The index of that bit can be used as the corresponding sum. When the bit is 1, means there is a sum with the value of its index. When a new number comes, this number needs to be added to all the previous sums, to form new "previous" sums. Thus for each number, we need to go through all the previous sums, the time co...

Priority_queue - Question 4

973 K Closest Points to Origin Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2). You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in). Constraints: 1 <= k <= points.length <= 10^4 -10^4 < xi, yi < 10^4 Analysis: It is quite straightforward to find the K points that have the closest distances to the original point. Since we need to find the smallest values, the root of the priority_queue (pq) is the largest one for all the elements inside the pq. Once the size of pq is larger than K, we need to pop out one. See the code below: class Solution { public: typedef pair<int, int> pp; vector<vector<int>> kClosest(vector<vector<int>>& points, int k) { vector...