Diwali Offer!Flat 20% OFF
Enroll Now
PrakalpanaLive online tech training

106. N-Queens

HardDay 32 of 60Recursion & Backtracking

Place n queens on an n x n chessboard so that no two queens attack each other (no two share a row, a column or a diagonal). Return every distinct arrangement. Each arrangement is a list of n strings, one per row, where Q is a queen and . is an empty square. The arrangements may be returned in any order.

Example 1
Input: n = 4
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
There are exactly two ways to place 4 queens safely.
Example 2
Input: n = 1
Output: [["Q"]]
Constraints
  • 1 <= n <= 9
Hints
Frequently asked at: Amazon, Microsoft, Apple, Samsung
Ctrl + Enter runs the examples

Not sure what to learn next?

A 1-on-1 session with an industry mentor and a roadmap built for you. How it works

  1. 1Discuss your goals
  2. 2Get a personal plan
  3. 3Start learning
Book for β‚Ή200/ 30 min