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

Graph Question - Hard Level - Question 1

2246. Longest Path With Different Adjacent Characters You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array parent of size n, where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1. You are also given a string s of length n, where s[i] is the character assigned to node i. Return the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them. Constraints: n == parent.length == s.length 1 <= n <= 10^5 0 <= parent[i] <= n - 1 for all i >= 1 parent[0] == -1 parent represents a valid tree. s consists of only lowercase English letters. Analysis For this question, we need to construct a graph, or more specifically, a n-nary tree. How to construct the graph/tree? What we only know is the parent array. So we need to go through the parent array and constr...

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