8 queen problem
Given an 8x8 chessboard, the task is to place 8 queens on the board such that no 2 queens threaten each other. Return a matrix of size 8x8, where 1 represents queen and 0 represents an empty position.

Approach:
The idea is to use backtracking to place the queens one by one on the board. Starting from the first row, we try placing queens in different columns and check if it's safe (not under attack from previously placed queens). If a safe position is found, we move to the next row. If at any point no safe position exists in a row, we backtrack to the previous row and try a different column placement. This recursive approach systematically explores all possible configurations until a valid solution is found.
Step by step approach:
- Initialize an empty 8×8 chessboard with all positions set to 0.
- Start with the first row (row 0) and try placing a queen in each column.
- For each placement, check if the position is safe (not attacked by any previously placed queen). A position is unsafe if another queen is in the same column or on the same diagonal.
- If a safe position is found, place the queen (set position to 1) and recursively try to place queens in subsequent rows. Otherwise, backtrack by removing the queen and trying the next column.
- If all rows are successfully filled (8 queens placed), a valid solution is found.
// C++ program to implement 8 queen problem
#include <bits/stdc++.h>
using namespace std;
// Function to check if it is safe to place
// the queen at board[row][col]
bool isSafe(vector<vector<int>>& mat, int row, int col) {
int n = mat.size();
int i, j;
// Check this col on upper side
for (i = 0; i < row; i++)
if (mat[i][col])
return false;
// Check upper diagonal on left side
for (i = row-1, j = col-1; i >= 0 &&
j >= 0; i--, j--)
if (mat[i][j])
return false;
// Check lower diagonal on left side
for (i = row-1, j = col+1; j < n &&
i >= 0; i--, j++)
if (mat[i][j])
return false;
return true;
}
bool placeQueens(int row, vector<vector<int>>& mat) {
int n = mat.size();
// base case: If all queens are placed
// then return true
if(row == n) return true;
// Consider the row and try placing
// queen in all columns one by one
for(int i = 0; i < n; i++){
// Check if the queen can be placed
if(isSafe(mat, row, i)){
mat[row][i] = 1;
if(placeQueens(row + 1, mat))
return true;
mat[row][i] = 0;
}
}
return false;
}
// Function to find the solution
// to the 8-Queens problem
vector<vector<int>> queens() {
int n = 8;
// Initialize the board
vector<vector<int>> mat(n, vector<int>(n, 0));
placeQueens(0, mat);
return mat;
}
int main() {
vector<vector<int>> res = queens();
for (auto v: res) {
for (auto square: v) {
cout << square << " ";
}
cout << endl;
}
return 0;
}
// Java program to implement 8 queen problem
import java.util.*;
class GfG {
// Function to check if it is safe to place
// the queen at board[row][col]
static boolean isSafe(int[][] mat, int row, int col) {
int n = mat.length;
int i, j;
// Check this col on upper side
for (i = 0; i < row; i++)
if (mat[i][col] == 1)
return false;
// Check upper diagonal on left side
for (i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--)
if (mat[i][j] == 1)
return false;
// Check lower diagonal on left side
for (i = row - 1, j = col + 1; j < n && i >= 0; i--, j++)
if (mat[i][j] == 1)
return false;
return true;
}
static boolean placeQueens(int row, int[][] mat) {
int n = mat.length;
// base case: If all queens are placed
// then return true
if (row == n) return true;
// Consider the row and try placing
// queen in all columns one by one
for (int i = 0; i < n; i++) {
// Check if the queen can be placed
if (isSafe(mat, row, i)) {
mat[row][i] = 1;
if (placeQueens(row + 1, mat))
return true;
mat[row][i] = 0;
}
}
return false;
}
// Function to find the solution
// to the 8-Queens problem
static int[][] queens() {
int n = 8;
// Initialize the board
int[][] mat = new int[n][n];
placeQueens(0, mat);
return mat;
}
public static void main(String[] args) {
int[][] res = queens();
for (int[] v : res) {
for (int square : v) {
System.out.print(square + " ");
}
System.out.println();
}
}
}
# Python program to implement 8 queen problem
# Function to check if it is safe to place
# the queen at board[row][col]
def isSafe(mat, row, col):
n = len(mat)
# Check this col on upper side
for i in range(row):
if mat[i][col]:
return False
# Check upper diagonal on left side
i, j = row - 1, col - 1
while i >= 0 and j >= 0:
if mat[i][j]:
return False
i -= 1
j -= 1
# Check lower diagonal on left side
i, j = row - 1, col + 1
while i >= 0 and j < n:
if mat[i][j]:
return False
i -= 1
j += 1
return True
def placeQueens(row, mat):
n = len(mat)
# base case: If all queens are placed
# then return true
if row == n:
return True
# Consider the row and try placing
# queen in all columns one by one
for i in range(n):
# Check if the queen can be placed
if isSafe(mat, row, i):
mat[row][i] = 1
if placeQueens(row + 1, mat):
return True
mat[row][i] = 0
return False
# Function to find the solution
# to the 8-Queens problem
def queens():
n = 8
# Initialize the board
mat = [[0] * n for _ in range(n)]
placeQueens(0, mat)
return mat
if __name__ == "__main__":
res = queens()
for v in res:
print(" ".join(map(str, v)))
// C# program to implement 8 queen problem
using System;
class GfG {
// Function to check if it is safe to place
// the queen at board[row][col]
static bool isSafe(int[,] mat, int row, int col) {
int n = mat.GetLength(0);
int i, j;
// Check this col on upper side
for (i = 0; i < row; i++)
if (mat[i, col] == 1)
return false;
// Check upper diagonal on left side
for (i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--)
if (mat[i, j] == 1)
return false;
// Check lower diagonal on left side
for (i = row - 1, j = col + 1; j < n && i >= 0; i--, j++)
if (mat[i, j] == 1)
return false;
return true;
}
static bool placeQueens(int row, int[,] mat) {
int n = mat.GetLength(0);
// base case: If all queens are placed
// then return true
if (row == n) return true;
// Consider the row and try placing
// queen in all columns one by one
for (int i = 0; i < n; i++) {
// Check if the queen can be placed
if (isSafe(mat, row, i)) {
mat[row, i] = 1;
if (placeQueens(row + 1, mat))
return true;
mat[row, i] = 0;
}
}
return false;
}
// Function to find the solution
// to the 8-Queens problem
static int[,] queens() {
int n = 8;
// Initialize the board
int[,] mat = new int[n, n];
placeQueens(0, mat);
return mat;
}
static void Main() {
int[,] res = queens();
int n = res.GetLength(0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Console.Write(res[i, j] + " ");
}
Console.WriteLine();
}
}
}
// JavaScript program to implement 8 queen problem
// Function to check if it is safe to place
// the queen at board[row][col]
function isSafe(mat, row, col) {
let n = mat.length;
// Check this col on upper side
for (let i = 0; i < row; i++)
if (mat[i][col])
return false;
// Check upper diagonal on left side
for (let i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--)
if (mat[i][j])
return false;
// Check lower diagonal on left side
for (let i = row - 1, j = col + 1; j < n && i >= 0; i--, j++)
if (mat[i][j])
return false;
return true;
}
function placeQueens(row, mat) {
let n = mat.length;
// base case: If all queens are placed
// then return true
if (row === n) return true;
// Consider the row and try placing
// queen in all columns one by one
for (let i = 0; i < n; i++) {
// Check if the queen can be placed
if (isSafe(mat, row, i)) {
mat[row][i] = 1;
if (placeQueens(row + 1, mat))
return true;
mat[row][i] = 0;
}
}
return false;
}
// Function to find the solution
// to the 8-Queens problem
function queens() {
let n = 8;
// Initialize the board
let mat = Array.from({ length: n }, () => Array(n).fill(0));
placeQueens(0, mat);
return mat;
}
let res = queens();
for (let row of res) {
console.log(row.join(" "));
}
Output
1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0
Related Articles: