Golang program to implement N queens problem


N queen problem is a puzzle in which N queens are to be placed on a NXN chessboard, so that the two queens don’t share the same row, column and diagonal or attack each other. A queen in chess can move in any direction, horizontally, vertically and diagonally so it is a challenge to find places where no two queens can attack each other. In this article, we will write a Go language program to implement the N queens problem.

Syntax

func make ([] type, size, capacity)

The make function in go language is used to create an array/map it accepts the type of variable to be created, its size and capacity as arguments

func append(slice, element_1, element_2…, element_N) []T

The append function is used to add values to an array slice. It takes number of arguments. The first argument is the array to which we wish to add the values followed by the values to add. The function then returns the final slice of array containing all the values.

Algorithm

  • Step 1 − Create a function named is_safe to check whether if it is safe to place a queen at a given position on the board

  • Step 2 − This function also checks if there are any queens in the same column, upper-left diagonal, and upper-right diagonal

  • Step 3 − Create a function solveN_queens that takes the current state of the board, the current row, the size of the board N, and a pointer to the outputs. In this step, check if we row==N, If it is true add solution to the list of outputs

  • Step 4 − Iterate over all columns in the current row and Check if it is safe to place a queen at the current position. Go forward with next steps if the former condition is satisfied

  • Step 5 − Set the current position as occupied by a queen (board[row][col] = true).

  • Step 6 − Recursively call solveN_queens for the next row (row+1), After the recursive call, backtrack by setting the current position as unoccupied, After the loop ends, the function solveN_queens returns after the loop ends

  • Step 7 − In the main function, create the board as a 2D slice of Booleans and call solveN_queens with board, row, output array and size as parameters

  • Step 8 − Finally, iterate over the outputs list and print the output on the console using Println function from the fmt package

Example

In this example, we will write a Go language program to implement N queens using backtracking algorithm using an NXN board and placing each queen on the board recursively.

package main

import "fmt"

func is_safe(board [][]bool, row, col, N int) bool {

   for i := 0; i < row; i++ {
      if board[i][col] {
         return false
      }
   }

   for i, j := row-1, col-1; i >= 0 && j >= 0; i, j = i-1, j-1 {
      if board[i][j] {
         return false
      }
   }

   for i, j := row-1, col+1; i >= 0 && j < N; i, j = i-1, j+1 {
      if board[i][j] {
         return false
      }
   }

   return true
}

func solveN_queens(board [][]bool, row, N int, outputs *[][]int) {
   if row == N {

      var output []int
      for i := 0; i < N; i++ {
         for j := 0; j < N; j++ {
            if board[i][j] {
               output = append(output, j+1)
               break
            }
         }
      }
      *outputs = append(*outputs, output)
      return
   }

   for col := 0; col < N; col++ {
      if is_safe(board, row, col, N) {

         board[row][col] = true

         solveN_queens(board, row+1, N, outputs)

         board[row][col] = false
      }
   }
}

func main() {
   n := 5
   board := make([][]bool, n)
   for i := 0; i < n; i++ {
      board[i] = make([]bool, n)
   }

   var outputs [][]int
   solveN_queens(board, 0, n, &outputs)

   for _, output := range outputs {
      fmt.Println(output)
   }
}

Output

[1 3 5 2 4]
[1 4 2 5 3] 
[2 4 1 3 5]
[2 5 3 1 4]
[3 1 4 2 5]
[3 5 2 4 1] 
[4 1 3 5 2] 
[4 2 5 3 1] 
[5 2 4 1 3] 
[5 3 1 4 2]

Output Observation

In the first solution the queens are arranged in the first column of the first row, the third column of the second row, the fifth column of the third row, the second column of the fourth row, the fourth column of the fifth row. The N queen problem may have multiple solutions and the above code will find all the valid solutions.

Conclusion

In this article we discussed how to implement the N queen problem. We have executed the program of implementing N queens problem using an example in which we used backtracking. Implementing N queen problems help you to increase your problem-solving and algorithm design abilities.

Updated on: 05-Jul-2023

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements