Eight Queen Problem With Complete Solution In C

Many successful programmers know more than just a computer language. They also know how to think about solving problems. They use “computational thinking", i.e., breaking a problem down into segments that lend themselves to technical solution. Here, I took a real life problem and solved the problem in computer language. This time, I have taken a very famous problem known as the Eight Queen Problem.
 
Now, the question arises what is an "Eight Queen Problem"? The Eight Queen Problem, also known as Eight Queen Puzzle, is a problem of placing eight queens on an 8 x 8 chessboard so that none of them attack one another. By attacking, we mean no two are in the same row, column or diagonal. Eight Queen Problem is a form of more generalized problem known as N Queen Problem or N Queen Puzzle where you have to place the N queens on an N x N chessboard such a way that none of them attack one another.
 
Before we begin to solve, there are some prerequisites that all my readers must fulfill. As it is clear from the article that we are going to solve the problem in C language, the readers must be familiar with C. Also, the readers must know the fundamentals of arrays and recursion and how to use them. Before jumping to my solution, I request you to try to create your own solution. This will help in developing your own logic. So, let’s begin.

There are two possible solutions to this problem. One is called the Naive algorithm and the other one is called Backtracking Algorithm.

Naive Algorithm

In Naive Algorithm, we generate all possible configurations of queen on board and test each configuration until we find a configuration which satisfies all the conditions. This solution looks quite easy but it takes a lot of time, especially when the value of N is higher. As the size of the problem grows, the number of configuration also grows exponentially and so is the time.

Backtracking algorithm

In this method, we place the queens one by one in different columns starting from the leftmost column. Whenever we place a queen in a column, we check for clashes with already placed queens. If there is no clash, we mark this row and column as part of the solution. If we are unable to find a row to place the queen due to clashes, then we backtrack and return false. This means that the solution does not exist.

 You can see the source code below.
  1. #include < stdio.h >   
  2. #include < conio.h >   
  3. #include < Windows.h >   
  4. #define N 8  
  5. //This method is used to color the characters  
  6. void Color(int col) {  
  7.     HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);  
  8.     SetConsoleTextAttribute(hConsole, col);  
  9. }  
  10. //This method print the final solution  
  11. void printSolution(int board[N][N]) {  
  12.     for (int i = 0; i < N; i++) {  
  13.         for (int j = 0; j < N; j++) {  
  14.             if (board[i][j] == 1) {  
  15.                 Color(2);  
  16.                 printf("%d ", board[i][j]);  
  17.             } else {  
  18.                 Color(15);  
  19.                 printf("%d ", board[i][j]);  
  20.             }  
  21.         }  
  22.         printf("\n");  
  23.     }  
  24. }  
  25. //This method checks whether it is safe to place the queen in particular row and column.  
  26. //This will return true if it is safe to place the queen and false otherwise.  
  27. bool isSafe(int board[N][N], int row, int col) {  
  28.     int i, j;  
  29.     /* Check this row on left side */  
  30.     for (i = 0; i < col; i++)  
  31.         if (board[row][i]) return false;  
  32.     /* Check upper diagonal on left side */  
  33.     for (i = row, j = col; i >= 0 && j >= 0; i--, j--)  
  34.         if (board[i][j]) return false;  
  35.     /* Check lower diagonal on left side */  
  36.     for (i = row, j = col; j >= 0 && i < N; i++, j--)  
  37.         if (board[i][j]) return false;  
  38.     return true;  
  39. }  
  40. //A recursive utility problem to solve N queens problem.  
  41. bool solveNQUtil(int board[N][N], int col) {  
  42.     /* base case: If all queens are placed 
  43.     then return true */  
  44.     if (col >= N) return true;  
  45.     /* Consider this column and try placing 
  46.     this queen in all rows one by one */  
  47.     for (int i = 0; i < N; i++) {  
  48.         /* Check if queen can be placed on 
  49.         board[i][col] */  
  50.         if (isSafe(board, i, col)) {  
  51.             /* Place this queen in board[i][col] */  
  52.             board[i][col] = 1;  
  53.             /* recur to place rest of the queens */  
  54.             if (solveNQUtil(board, col + 1)) return true;  
  55.             /* If placing queen in board[i][col] 
  56.             doesn't lead to a solution, then 
  57.             remove queen from board[i][col] */  
  58.             board[i][col] = 0; // BACKTRACK  
  59.         }  
  60.     }  
  61.     /* If queen can not be place in any row in 
  62.     this colum col then return false */  
  63.     return false;  
  64. }  
  65. /* This function solves the N Queen problem using 
  66. Backtracking. It mainly uses solveNQUtil() to 
  67. solve the problem. It returns false if queens 
  68. cannot be placed, otherwise return true and 
  69. prints placement of queens in the form of 1s. 
  70. Please note that there may be more than one 
  71. solutions, this function prints one of the feasible soutions*/  
  72. bool solveNQ() {  
  73.     int board[N][N] = {  
  74.         {  
  75.             0,  
  76.             0,  
  77.             0,  
  78.             0  
  79.         },  
  80.         {  
  81.             0,  
  82.             0,  
  83.             0,  
  84.             0  
  85.         },  
  86.         {  
  87.             0,  
  88.             0,  
  89.             0,  
  90.             0  
  91.         },  
  92.         {  
  93.             0,  
  94.             0,  
  95.             0,  
  96.             0  
  97.         }  
  98.     };  
  99.     if (solveNQUtil(board, 0) == false) {  
  100.         printf("Solution does not exist");  
  101.         return false;  
  102.     }  
  103.     printSolution(board);  
  104.     return true;  
  105. }  
  106. int main() {  
  107.     solveNQ();  
  108.     _getch();  
  109.     return 0;  
  110. }  
That's all for today guys! You can visit my blog.