Showing posts with label Backtracking. Show all posts
Showing posts with label Backtracking. Show all posts

Friday, 3 November 2017

N Queens Chess Problem Solution using C++

The N Queens Problem 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 eight queens puzzle is an example of the N queens problem of placing N non-attacking queens on an N×N chessboard, for which solutions exist for all natural numbers N with the exception of N=2 and N=3.

In the code, backtracking method is used to solve the problem. A queen is placed in a column that is known not to cause conflict. If a column is not found the program returns to the last good state and then tries a different column by increments or decrements the column index.

//A C++ code to Solve N-Queen Chess problem

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <conio.h>

const unsigned int N = 8;
using namespace std;

// Print N Queen chess problem solution
void PrintNQSolution(bool board[N][N])
{
     for (int i = 0; i < N; i++)
     {
           for (int j = 0; j < N; j++)
                cout << board[i][j] << "  ";
           cout << endl;
     }
}

/* check if a queen can be placed on the board[row][col]*/
bool CheckSafe(bool board[N][N], int row, int col)
{
     int i, j;
     for (i = 0; i < col; i++)
     {
           if (board[row][i])
                return false;
     }
     for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
     {
           if (board[i][j])
                return false;
     }

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

     return true;
}

/*solve N Queen problem */
bool SolveNQ(bool board[N][N], int col)
{
     if (col >= N)
           return true;
     for (int i = 0; i < N; i++)
     {
           if (CheckSafe(board, i, col))
           {
                board[i][col] = true;
                if (SolveNQ(board, col + 1) == true)
                     return true;
                board[i][col] = false;
           }
     }
     return false;
}

/* solves the N Queen problem using Backtracking and print the solution.*/
bool SolveAndPrintNQ()
{
     bool board[N][N] = { 0 };
     if (SolveNQ(board, 0) == false)
     {
           cout << "Solution does not exist" << endl;
           return false;
     }
     PrintNQSolution(board);
     return true;
}

int main()
{
     cout << "**** " << N << " Queens Problem Solution *****\n\n";
     SolveAndPrintNQ();
     _getch();
     return 0;
}


Output:

Sunday, 10 September 2017

A Sudoku Problem Solver using C++

This C++ program demonstrates the Sudoku problem solver using Backtracking Method. We basically check that the same number is not present in current row, current column and current 3 x 3 sub grid. 

After checking for safety, we assign the number and recursively check whether this assignment leads to a solution or not. If the assignment does not lead to a solution, then we try next number for current empty cell and if none of number lead to solution we return false.

Source Code:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
#define UNASSIGNED 0
#define N 9

bool FindUnassignedLocation(int grid[N][N], int &row, int &col);
bool isSafe(int grid[N][N], int row, int col, int num);

/* assign values to all unassigned locations for Sudoku solution
*/
bool SolveSudoku(int grid[N][N])
{
       int row, col;
       if (!FindUnassignedLocation(grid, row, col))
              return true;
       for (int num = 1; num <= 9; num++)
       {
              if (isSafe(grid, row, col, num))
              {
                     grid[row][col] = num;
                     if (SolveSudoku(grid))
                           return true;
                     grid[row][col] = UNASSIGNED;
              }
       }
       return false;
}

/* Searches the grid to find an entry that is still unassigned. */
bool FindUnassignedLocation(int grid[N][N], int &rowint &col)
{
       for (row = 0; row < Nrow++)
              for (col = 0; col < Ncol++)
                     if (grid[row][col] == UNASSIGNED)
                           return true;
       return false;
}

/* Returns whether any assigned entry n the specified row matches
the given number. */
bool UsedInRow(int grid[N][N], int rowint num)
{
       for (int col = 0; col < N; col++)
              if (grid[row][col] == num)
                     return true;
       return false;
}

/* Returns whether any assigned entry in the specified column matches
the given number. */
bool UsedInCol(int grid[N][N], int colint num)
{
       for (int row = 0; row < N; row++)
              if (grid[row][col] == num)
                     return true;
       return false;
}

/* Returns whether any assigned entry within the specified 3x3 box matches
the given number. */
bool UsedInBox(int grid[N][N], int boxStartRowint boxStartColint num)
{
       for (int row = 0; row < 3; row++)
              for (int col = 0; col < 3; col++)
                     if (grid[row + boxStartRow][col + boxStartCol] == num)
                           return true;
       return false;
}

/* Returns whether it will be legal to assign num to the given row,col location.
*/
bool isSafe(int grid[N][N], int rowint colint num)
{
       return !UsedInRow(gridrownum) && !UsedInCol(gridcolnum) &&
              !UsedInBox(gridrow - row % 3, col - col % 3, num);
}

/* print grid  */
void printGrid(int grid[N][N])
{
       for (int row = 0; row < N; row++)
       {
              for (int col = 0; col < N; col++)
                     cout << grid[row][col] << "  ";
              cout << endl;
       }
}

/* Main */
int main()
{
       int grid[N][N] =
       {
              { 8, 0, 0, 0, 0, 0, 0, 0, 0 },
              { 0, 0, 3, 6, 0, 0, 0, 0, 0 },
              { 0, 7, 0, 0, 9, 0, 2, 0, 0 },
              { 0, 5, 0, 0, 0, 7, 0, 0, 0 },
              { 0, 0, 0, 0, 4, 5, 7, 0, 0 },
              { 0, 0, 0, 1, 0, 0, 0, 3, 0 },
              { 0, 0, 1, 0, 0, 0, 0, 6, 8 },
              { 0, 0, 8, 5, 0, 0, 0, 1, 0 },
              { 0, 9, 0, 0, 0, 0, 4, 0, 0 }
       };

       if (SolveSudoku(grid) == true)
              printGrid(grid);
       else
              cout << "No solution exists" << endl;
       getchar();
       return 0;
}

Output: