Skip to content

4. N Queen

Ardous

Description

The N-Queens problem is a classic constraint satisfaction problem in computer science and mathematics. Given an N x N chessboard, the challenge is to place N queens such that no two queens attack each other. Queens can attack horizontally, vertically, and diagonally.

Example_1_img

Constraints:

  • 1 <= N <= 20
  • Each queen must be placed such that no two queens can attack each other

๐Ÿš€ Test your code

Try to solve the problem below in the code editor before reading the solution.

Results

View Result
For N = 8: 92 solutions found
For N = 12: 14200 solutions found
For N = 16: 14772512 solutions found

Example solution for N = 8:
Queen positions: [(1,1), (2,5), (3,8), (4,6), (5,3), (6,7), (7,2), (8,4)]

Board visualization:

block-beta
    columns 8
    Q1["โ™›"]:1
    E2[" "]:1
    E3[" "]:1
    E4[" "]:1
    E5[" "]:1
    E6[" "]:1
    E7[" "]:1
    E8[" "]:1

    F1[" "]:1
    F2[" "]:1
    F3[" "]:1
    F4[" "]:1
    Q2["โ™›"]:1
    F6[" "]:1
    F7[" "]:1
    F8[" "]:1

    G1[" "]:1
    G2[" "]:1
    G3[" "]:1
    G4[" "]:1
    G5[" "]:1
    G6[" "]:1
    G7[" "]:1
    Q3["โ™›"]:1

    H1[" "]:1
    H2[" "]:1
    H3[" "]:1
    H4[" "]:1
    H5[" "]:1
    Q4["โ™›"]:1
    H7[" "]:1
    H8[" "]:1

    I1[" "]:1
    I2[" "]:1
    Q5["โ™›"]:1
    I4[" "]:1
    I5[" "]:1
    I6[" "]:1
    I7[" "]:1
    I8[" "]:1

    J1[" "]:1
    J2[" "]:1
    J3[" "]:1
    J4[" "]:1
    J5[" "]:1
    J6[" "]:1
    Q6["โ™›"]:1
    J8[" "]:1

    K1[" "]:1
    Q7["โ™›"]:1
    K3[" "]:1
    K4[" "]:1
    K5[" "]:1
    K6[" "]:1
    K7[" "]:1
    K8[" "]:1

    L1[" "]:1
    L2[" "]:1
    L3[" "]:1
    Q8["โ™›"]:1
    L5[" "]:1
    L6[" "]:1
    L7[" "]:1
    L8[" "]:1

    classDef queen fill:#ff6b6b,stroke:#333,stroke-width:2px,color:#fff
    classDef empty fill:#f9f9f9,stroke:#ddd,stroke-width:1px

    class Q1,Q2,Q3,Q4,Q5,Q6,Q7,Q8 queen
Press "Alt" / "Option" to enable Pan & Zoom

Answer ๐Ÿ”’

Comments