Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Backtracking
  • Interview Problems on Backtracking
  • MCQs on Backtracking
  • Tutorial on Backtracking
  • Backtracking vs Recursion
  • Backtracking vs Branch & Bound
  • Print Permutations
  • Subset Sum Problem
  • N-Queen Problem
  • Knight's Tour
  • Sudoku Solver
  • Rat in Maze
  • Hamiltonian Cycle
  • Graph Coloring
Open In App
Next Article:
N Queen Problem using Branch And Bound
Next article icon

8 queen problem

Last Updated : 16 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

ApronusDiagram1595653398

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:

  1. Initialize an empty 8×8 chessboard with all positions set to 0.
  2. Start with the first row (row 0) and try placing a queen in each column.
  3. 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.
  4. 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.
  5. If all rows are successfully filled (8 queens placed), a valid solution is found.
C++
// 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
// 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
# 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#
// 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
// 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:

  • N Queen Problem
  • N Queen Problem using Branch And Bound

Next Article
N Queen Problem using Branch And Bound

K

kartik
Improve
Article Tags :
  • Backtracking
  • DSA
  • chessboard-problems
Practice Tags :
  • Backtracking

Similar Reads

    N Queen Problem
    Given an integer n, the task is to find the solution to the n-queens problem, where n queens are placed on an n*n chessboard such that no two queens can attack each other. The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example,
    15+ min read

    N-Queen in Different languages

    Java Program for N Queen Problem | Backtracking-3
    The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, the following is a solution for 4 Queen problem. The expected output is a binary matrix which has 1s for the blocks where queens are placed. For example, following is the o
    4 min read
    Python Program for N Queen Problem | Backtracking-3
    The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, the following is a solution for 4 Queen problem. The expected output is a binary matrix that has 1s for the blocks where queens are placed. For example, the following is th
    3 min read
    C Program for N Queen Problem | Backtracking-3
    The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, the following is a solution for 4 Queen problem. The expected output is a binary matrix which has 1s for the blocks where queens are placed. For example, the following is t
    3 min read
    4 Queens Problem
    The 4 Queens Problem consists in placing four queens on a 4 x 4 chessboard so that no two queens attack each other. That is, no two queens are allowed to be placed on the same row, the same column or the same diagonal. We are going to look for the solution for n=4 on a 4 x 4 chessboard in this artic
    15 min read
    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
    9 min read
    N Queen Problem using Branch And Bound
    The N queens puzzle is the problem of placing N chess queens on an N×N chessboard so that no two queens threaten each other. Thus, a solution requires that no two queens share the same row, column, or diagonal. The backtracking Algorithm for N-Queen is already discussed here. In a backtracking solut
    15+ min read
    N Queen in O(n) space
    Given an integer n, the task is to find the solution to the n-queens problem, where n queens are placed on an n*n chessboard such that no two queens can attack each other.The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other.For example, th
    7 min read
    Printing all solutions in N-Queen Problem
    Given an integer n, the task is to find all distinct solutions to the n-queens problem, where n queens are placed on an n * n chessboard such that no two queens can attack each other. Note: Each solution is a unique configuration of n queens, represented as a permutation of [1,2,3,....,n]. The numbe
    15+ min read
    Minimum queens required to cover all the squares of a chess board
    Given the dimension of a chess board (N x M), determine the minimum number of queens required to cover all the squares of the board. A queen can attack any square along its row, column or diagonals. Examples: Input : N = 8, M = 8Output : 5Layout : Q X X X X X X X X X Q X X X X X X X X X Q X X X X Q
    14 min read
    Number of cells a queen can move with obstacles on the chessboard
    Consider a N X N chessboard with a Queen and K obstacles. The Queen cannot pass through obstacles. Given the position (x, y) of Queen, the task is to find the number of cells the queen can move. Examples: Input : N = 8, x = 4, y = 4, K = 0 Output : 27 Input : N = 8, x = 4, y = 4, K = 1, kx1 = 3, ky1
    15+ min read
    N-Queen Problem | Local Search using Hill climbing with random neighbour
    The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, the following is a solution for 8 Queen problem. Input: N = 4 Output: 0 1 0 0 0 0 0 1 1 0 0 0 0 0 1 0 Explanation: The Position of queens are: 1 - {1, 2} 2 - {2, 4} 3 - {3,
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences