Fun with Backtracking - The N Queen Problem

So today I will be talking about backtracking algorithm, one of my most favorite algorithms. Maybe it's just because of the name "backtracking" or just the reason being it avoids all the collusion or problems. A peaceful environment I would say. So let's hop into the problem .

What is backtracking ?

In backtracking algorithms we try to build a solution one step at a time. If at some step it becomes clear that the current path that we are on cannot lead to a solution we go back to the previous step (backtrack) and choose a different path. Basically once we exhaust all our options at a certain step we go back. The classic example for backtracking is the Eight Queen Problem.

N Queen Problem :

The idea is to place queens one by one in different columns, starting from the leftmost column. When we place a queen in a column, we check for clashes with already placed queens. In the current column, if we find a row for which there is no clash, we mark this row and column as part of the solution. If we do not find such a row due to clashes then we backtrack and return false.

1. Start in the leftmost column.
2. If all queens are placed. return true.
3. Try all rows in the current column. Do following for every tried row.

 a. If the queen can be placed safely in this row then mark this [row, 
column] as part of the solution and recursively check if placing queen here leads to a solution.
 b. If placing queen in [row, column] leads to a solution then return true.
 c. If placing queen doesn't lead to a solution then umark this [row, column] (Backtrack) and go to step (a) to try other rows.

4. If all rows have been tried and nothing worked, return false to trigger 
backtracking. 

  1. using System.Collections.Generic;  
  2. using System.Linq;  
  3. using System.Text;  
  4. using System.Threading.Tasks;  
  5. namespace Backtracking {  
  6.     class Program {  
  7.         static int N;  
  8.         static void printBoard(int[, ] board) {  
  9.             for (int i = 0; i < N; i++) {  
  10.                 for (int j = 0; j < N; j++) {  
  11.                     Console.Write(board[i, j] + " ");  
  12.                 }  
  13.                 Console.Write("\n");  
  14.             }  
  15.         }  
  16.         static Boolean toPlaceOrNotToPlace(int[, ] board, int row, int col) {  
  17.             int i, j;  
  18.             for (i = 0; i < col; i++) {  
  19.                 if (board[row, i] == 1) return false;  
  20.             }  
  21.             for (i = row, j = col; i >= 0 && j >= 0; i--, j--) {  
  22.                 if (board[i, j] == 1) return false;  
  23.             }  
  24.             for (i = row, j = col; j >= 0 && i < N; i++, j--) {  
  25.                 if (board[i, j] == 1) return false;  
  26.             }  
  27.             return true;  
  28.         }  
  29.         static Boolean theBoardSolver(int[, ] board, int col) {  
  30.             if (col >= N) return true;  
  31.             for (int i = 0; i < N; i++) {  
  32.                 if (toPlaceOrNotToPlace(board, i, col)) {  
  33.                     board[i, col] = 1;  
  34.                     if (theBoardSolver(board, col + 1)) return true;  
  35.                     // Backtracking is hella important in this one.  
  36.                     board[i, col] = 0;  
  37.                 }  
  38.             }  
  39.             return false;  
  40.         }  
  41.         static void Main(string[] args) {  
  42.             Console.WriteLine("State the value of N in this program!");  
  43.             N = Convert.ToInt32(Console.ReadLine());  
  44.             int[, ] board = new int[N, N];  
  45.             if (!theBoardSolver(board, 0)) {  
  46.                 Console.WriteLine("Solution not found.");  
  47.             }  
  48.             printBoard(board);  
  49.             Console.ReadLine();  
  50.         }  
  51.     }  
  52. }  

Ok !! That's it . Next we will be discussing another problem, obviously the one I like better :p .

This is just my second article . I will expect constructive suggestions from seniors.

Read more articles on C#:

Up Next
    Ebook Download
    View all
    Learn
    View all