Home » Eight Queens Puzzle!

Eight Queens Puzzle!

Solving Eight Queens Puzzle challenge by Power Query, Power BI, Excel, Python and R

Theeight-queenss puzzle is the problem of placing eight chess queens on an 8×8 chessboard so that no two queens threaten each other; thus, a solution requires that no two queens share the same row, column, or diagonal. In the question table, I have indicated the location of a queen with “Q”. Please determine the positions of the other queens on the board. It would be ideal if the solution is dynamic so that if the location of the first queen changes, the positions of the other queens are updated accordingly.

📌 Challenge Details and Links
Challenge Number: 150
Challenge Difficulty: ⭐⭐⭐⭐⭐⭐
📥Download Sample File
📥Link to the solutions on LinkedIn

Solving the challenge of Eight Queens Puzzle! with Power Query

Power Query solution 1 for Eight Queens Puzzle!, proposed by Omid Motamedisedeh:
let
 Position= List.PositionOf(List.Combine(Table.ToRows(Table.RemoveColumns(Excel.CurrentWorkbook(){[Name="Table2"]}[Content],"Column1"))),"Q",Occurrence.All),
Power Query solution 2 for Eight Queens Puzzle!, proposed by Omid Motamedisedeh:
let
  P = List.PositionOf(
    List.Combine(
      Table.ToRows(
        Table.RemoveColumns(Excel.CurrentWorkbook(){[Name = "Table2"]}[Content], "Column1")
      )
    ), 
    "Q", 
    Occurrence.All
  ), 
  Blocked = (i) =>
    [
      a = Number.IntegerDivide(i, 8), 
      b = i - 8 * a, 
      l1 = List.RemoveNulls(
        List.Combine(
          List.Transform(
            {0 .. 7}, 
            each {
              b + _ * 8, 
              8 * a + _, 
              if _ < List.Min({a, b}) then (i - 9 * (_ + 1)) else null, 
              if _ < List.Min({a, 7 - b}) then i - 7 * (_ + 1) else null, 
              if _ < List.Min({7 - a, 7 - b}) then (i + 9 * (_ + 1)) else null, 
              if _ < List.Min({7 - a, b}) then (i + 7 * (_ + 1)) else null
            }
          )
        )
      )
    ][l1], 
  B = List.Combine(List.Transform(P, Blocked)), 
  NB = List.Difference({0 .. 63}, B), 
  FX = (P, B, NB) =>
    if List.Count(P) = 8 then
      P
    else if NB = {} then
      null
    else
      List.Transform(
        NB, 
        each [a = P & {_}, b = B & Blocked(_), c = @FX(a, b, List.Difference({0 .. 63}, b))][c]
      ), 
  Final = FX(P, B, NB), 
  X = List.Split(
    List.Accumulate({1 .. (8 - List.Count(P))}, Final, (a, b) => List.RemoveNulls(List.Combine(a))), 
    8
  ){0}, 
  Custom1 = Table.FromRows(
    List.Split(List.Transform({0 .. 63}, (x) => if List.Contains(X, x) then "Q" else ""), 8)
  )
in
  Custom1
Power Query solution 3 for Eight Queens Puzzle!, proposed by Alexis Olson:
let
  N = 8, 
  L = {1 .. N}, 
  Cols = {"a" .. "h"}, 
  Gen = List.Generate(
    () => [rows = List.Transform(L, each {_}), i = 1], 
    each [i] <= N, 
    each [
      rows = List.Combine(
        List.Transform(
          [rows], 
          (x) =>
            [
              neg    = {- List.Count(x) .. - 1}, 
              pos    = List.Transform(neg, (k) => - k), 
              diags  = List.Transform(List.Zip({x, pos}) & List.Zip({x, neg}), List.Sum), 
              nextQ  = List.Difference(L, x & diags), 
              append = List.Transform(nextQ, each x & {_})
            ][append]
        )
      ), 
      i = [i] + 1
    ]
  ), 
  AllSolutions = Table.AddColumn(
    Table.FromRows(List.Last(Gen)[rows], Cols), 
    "Board", 
    (row) =>
      Table.FromColumns(
        List.Transform(
          Record.FieldValues(row), 
          (j) => List.ReplaceRange(List.Repeat({null}, N), N - j, 1, {"Q"})
        ), 
        Cols
      )
  ), 
  Input = Excel.CurrentWorkbook(){[Name = "Table1"]}[Content], 
  Unpivot = Table.UnpivotOtherColumns(Input, {"Row"}, "Column", "Value"), 
  Matches = Table.SelectRows(
    AllSolutions, 
    (row) =>
      List.AllTrue(
        List.Transform(Table.ToRecords(Unpivot), each Record.Field(row, [Column]) = [Row])
      )
  ), 
  FirstMatch = List.First(Matches[Board])
in
  FirstMatch

Solving the challenge of Eight Queens Puzzle! with Excel

Excel solution 1 for Eight Queens Puzzle!, proposed by Bo Rydobon 🇹🇭:
=LET(r,
    SEQUENCE(
        8
    ),
    c,
    TOROW(
        r
    ),
    rc,
    r*100+c,REDUCE(TAKE(
    rc,
    1
),
    DROP(
        r,
        1
    ),
    LAMBDA(d,
    _,
    DROP(REDUCE(0,
    d,
    LAMBDA(h,
    q,
    LET(
b,
    REDUCE(1,
    --TEXTSPLIT(
        q,
        " "
    ),
    LAMBDA(a,
    q,
    LET(i,
    INT(
        q/100
    ),
    j,
    MOD(
        q,
        100
    ),
    a*(i<>r)*(j<>c)*(ABS(
        i-r
    )<>ABS(
        j-c
    ))))),p,
    q&" "&TOCOL(IFS((MIN(
        IF(
            b,
            r
        )
    )=r)*b,
    rc),
    3),IF(
    ISERR(
        @p
    ),
    h,
    VSTACK(
        h,
        p
    )
)))),
    1))))
Excel solution 2 for Eight Queens Puzzle!, proposed by Bo Rydobon 🇹🇭:
=LET(r,
    SEQUENCE(
        8
    ),
    c,
    TOROW(
        r
    ),
    rc,
    r*100+c,B,
    LAMBDA(b,
    a,
    LET(n,
    ROWS(
        a
    ),
    IF(n=1,
    LET(q,
    REDUCE(rc^0,
    TEXTSPLIT(
        @a,
        "-"
    ),
    LAMBDA(a,
    v,
    LET(i,
    INT(
        v/100
    ),
    j,
    MOD(
        v,
        100
    ),
    a*(r<>i)*(c<>j)*(ABS(
        r-i
    )<>ABS(
        c-j
    ))))),
    i,
    IF(
        q,
        r
    ),
    TOCOL(a&-TOROW(IFS(q*(r=MIN(
        i
    )),
    rc),
    3))),
    VSTACK(
        b(
            b,
            TAKE(
                a,
                n/2
            )
        ),
        b(
            b,
            DROP(
                a,
                n/2
            )
        )
    )))),rs,
    REDUCE(MAX((C3:J10="Q")*rc),
    SEQUENCE(
        7
    ),
    LAMBDA(
        ij,
        _,
        TOCOL(
            B(
                B,
                ij
            ),
            3
        )
    )),REDUCE(
    IF(
        c,
        "_"
    ),
    rs,
    LAMBDA(
        a,
        x,        VSTACK(
            a,
            REPT(
                "Q",
                ISNUMBER(
                    XMATCH(
                        rc,
                        --TEXTSPLIT(
                            x,
                            "-"
                        )
                    )
                )
            ),
            IF(
                c,
                "_"
            )
        )
    )
))
Excel solution 3 for Eight Queens Puzzle!, proposed by Kris Jaganah:
=LET(
    a,
    B3:B10,
    b,
    C2:J2,
    c,
    C3:J10,
    d,
    TOCOL(
        IF(
            c="",
            jj,
            a&b
        ),
        3
    ),
    e,
    SCAN(
        ARRAYTOTEXT(
            d
        ),
        SEQUENCE(
            8-ROWS(
            d
        )
        ),
        LAMBDA(
            r,
            s,
            LET(
                i,
                TEXTSPLIT(
                    r,
                    ,
                    ", "
                ),
                j,
                DROP(
                    TOCOL(
                        REDUCE(
                            "",
                            i,
                            LAMBDA(
                                v,
                                w,
                                VSTACK(
                                    v,
                                    LET(
                                        n,
                                        TOCOL(
                                            a&b
                                        ),
                                        p,
                                        TOROW(
                                            LEFT(
                                                w
                                            )+{1,
                                            -1}&CHAR(
                                                CODE(
                                                    RIGHT(
                                                w
                                            )
                                                )+{1;-1}
                                            )
                                        ),
                                        q,
                                        TOROW(
                                            MAP(
                                                n,
                                                LAMBDA(
                                                    x,
                                                    FILTER(
                                                        p,
                                                        p=x
                                                    )
                                                )
                                            ),
                                            3
                                        ),
                                        q
                                    )
                                )
                            )
                        ),
                        3
                    ),
                    1
                ),
                k,
                VSTACK(
                    i,
                    j
                ),
                l,
                TOCOL(
                    TEXTSPLIT(
                        TOCOL(
                            TOCOL(
                                TEXTSPLIT(
                                    a,
                                    LEFT(
                                        i
                                    ),
                                    ,
                                    1
                                ),
                                3
                            )&TOROW(
                                TEXTSPLIT(
                                    b,
                                    RIGHT(
                                        i
                                    ),
                                    ,
                                    1
                                ),
                                3
                            )
                        ),
                        k,
                        ,
                        1
                    ),
                    3
                ),
                ARRAYTOTEXT(
                    VSTACK(
                        i,
                        TAKE(
                            l,
                            1
                        )
                    )
                )
            )
        )
    ),
    IFERROR(
        TAKE(
            TOCOL(
                e,
                3
            ),
            -1
        ),
        ARRAYTOTEXT(
            d
        )
    )
)
Excel solution 4 for Eight Queens Puzzle!, proposed by LEONARD OCHEA 🇷🇴:
=LET(
  n,
  8,
  s,
  SEQUENCE(
    ,
    n
  ),
  DROP(
    REDUCE(
      "",
      s,
      LAMBDA(
        u,
        t,
        VSTACK(
          u,
          TEXTSPLIT(
            REDUCE(
              t,
              DROP(
                s,
                ,
                -1
              ),
              LAMBDA(
                h,
                k,
                REDUCE(
                  "",
                  TEXTSPLIT(
                    h,
                    ","
                  ),
                  LAMBDA(
                    o,
                    p,
                    LET(
                      i,
                      TEXTSPLIT(
                        p,
                        "|"
                      ),
                      j,
                      COLUMNS(
                        i
                      ),
                      TEXTJOIN(
                        ",",
                        ,
                        o,
                        IFERROR(
                          p&"|"&FILTER(
                            s,
                            TAKE(
                              IFERROR(
                                REDUCE(
                                  0,
                                  SEQUENCE(
                                    j
                                  ),
                                  LAMBDA(
                                    a,
                                    b,
                                    LET(
                                      z,
                                      --INDEX(
                                        i,
                                        b
                                      ),
                                      a+MAKEARRAY(
                                        j+1,
                                        n,
                                        LAMBDA(
                                          f,
                                          c,
                                          N(
                                            c=z-b+f
                                          )+N(
                                            c=b+z-f
                                          )+N(
                                            f=b
                                          )+N(
                                            c=z
                                          )
                                        )
                                      )
                                    )
                                  )
                                ),
                                ""
                              ),
                              -1
                            )=0
                          ),
                          ""
                        )
                      )
                    )
                  )
                )
              )
            ),
            ,
            ","
          )
        )
      )
    ),
    1
  )
)
Excel solution 5 for Eight Queens Puzzle!, proposed by Pieter de B.:
=LET(s,
    SEQUENCE(
        8
    ),
    REDUCE(C3:J10,
    DROP(
        s,
        1
    ),
    LAMBDA(x,
    y,
    LET(r,
    TOCOL(
        IFS(
            x="Q",
            s
        ),
        2
    ),
    c,
    TOROW(
        IFS(
            x="Q",
            TOROW(
                s
            )
        ),
        2
    ),
    IF((s=@UNIQUE(
        VSTACK(
            r,
            s
        ),
        ,
        1
    ))*(TOROW(
                s
            )=@UNIQUE(
        HSTACK(
            c,
            TOROW(
                s
            )
        ),
        1,
        1
    )),
    "Q",
    x)))))

Solving the challenge of Eight Queens Puzzle! with Python in Excel

Python in Excel solution 1 for Eight Queens Puzzle!, proposed by Alejandro Campos:
def free(row, col):
 for i in range(8): 
 if board[row][i] == 'Q' or board[i][col] == 'Q':
 return False
 if row <= col:
 c = col - row
 r = 0
 else:
 r = row - col
 c = 0
 while c < 8 and r < 8:
 if board[r][c] == 'Q':
 return False
 r += 1
 c += 1
 if row <= col:
 r = 0
 c = col + row
 if c > 7:
 r = c - 7
 c = 7
 else:
 c = 7
 r = row - (7 - col)
 while c >= 0 and r < 8:
 if board[r][c] == 'Q':
 return False
 r += 1
 c -= 1
 return True
def add_queen(n): 
 if n < 1:
 return True
 for idx_row in range(8):
 for idx_col in range(8):
 if free(idx_row, idx_col):
 board[idx_row][idx_col] = 'Q'
 if add_queen(n-1): 
 return True
 else:
 board[idx_row][idx_col] = ' '
 return False
board = [[' '] * 8 for _ in range(8)]
row_init = xl("AG3")
col_init = xl("AH3")
if 1 <= row_init <= 8 and 1 <= col_init <= 8:
 row_init -= 1
 col_init -= 1
board[row_init][col_init] = 'Q'
add_queen(7)
df_board = pd.DataFrame(board)
df_board

Solving the challenge of Eight Queens Puzzle! with Google Sheets

Google Sheets solution 1 for Eight Queens Puzzle!, proposed by Peter Krkos:
Hi Omid Motamedisedeh, I spent almost a day to with this task. It was easy to create a solution but excluding diagonals... I found a solution, but everytime I have to refresh few times to get correct result (because sometimes there are errors). Finally I helped myself with ChatGPT and it creates for me formula for all possible combinations (in yellow square). With this it was done in a few minutes :)
https://docs.google.com/spreadsheets/d/1zR5IZLz8OT76vhaPEHfsPrw8-RDKnLyyqS49IJjdhFk/edit?pli=1&gid=1846084489#gid=1846084489

Leave a Reply