Place the numbers 1, 2, 3, 4, 5, 6, 7, 8 into the eight circles in the figure given below, in such a way that no number is adjacent to a number that is next to it in the sequence. For example, 1 should not be adjacent to 2 but can be adjacent to 3, 4, 5, 6, 7, 8. Similarly for others.
Â
Â
Naive AlgorithmÂ
The Naive Algorithm is to generate all possible configurations of numbers from 1 to 8 to fill the empty cells. Try every configuration one by one until the correct configuration is found.
Backtracking AlgorithmÂ
Like all other Backtracking problems, we can solve this problem by one by one assigning numbers to empty cells. Before assigning a number, we check whether it is safe to assign. We basically check that the same number is not present to its adjacent cell (vertically, horizontally or diagonally). After checking for safety, we assign the number, and recursively check whether this assignment leads to a solution or not. If the assignment doesn’t lead to a solution, then we try next number for the current empty cell. And if none of the number (1 to 8) leads to solution, we return false.Â
Â
Find row, col of an unassigned cell
If there is none, return true
For digits from 1 to 8
a) If there is no conflict for digit at row, col
assign digit to row, col and recursively try fill in rest of grid
b) If recursion successful, return true
c) Else, remove digit and try another
If all digits have been tried and nothing worked, return false
Â
CPP
// A Backtracking program in// C++ to solve given problem#include <cmath>#include <iostream>Â
#define N 3 // row of grid#define M 4 // column of grid#define UNASSIGNED -1using namespace std;Â
/* Returns a boolean which indicateswhether any assigned entry within thespecified grid matches the given number. */bool UsedInGrid(int grid[N][M], int num){Â Â Â Â for (int i = 0; i < N; i++) {Â Â Â Â Â Â Â Â for (int j = 0; j < M; j++)Â Â Â Â Â Â Â Â Â Â Â Â if (grid[i][j] == num)Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â return true;Â Â Â Â }Â Â Â Â return false;}Â
/* Returns a boolean which indicateswhether it will be legal to assignnum to the given row, col location. */bool isSafe(int grid[N][M], int row, int col, int num){Â Â Â Â /* Check if 'num' is not already placed in Whole Grid*/Â Â Â Â if (row == 0 && col == 1) {Â
        if (UsedInGrid(grid, num)            || (abs(num - grid[row][col + 1]) <= 1)            || (abs(num - grid[row + 1][col]) <= 1)            || (abs(num - grid[row + 1][col - 1]) <= 1)            || (abs(num - grid[row + 1][col + 1]) <= 1))            return false;    }    else if (row == 0 && col == 2) {        if (UsedInGrid(grid, num)            || (abs(num - grid[row][col - 1]) <= 1)            || (abs(num - grid[row + 1][col]) <= 1)            || (abs(num - grid[row + 1][col + 1]) <= 1)            || (abs(num - grid[row + 1][col - 1]) <= 1))            return false;    }    else if (row == 1 && col == 0) {        if (UsedInGrid(grid, num)            || (abs(num - grid[row - 1][col + 1]) <= 1)            || (abs(num - grid[row][col + 1]) <= 1)            || (abs(num - grid[row + 1][col + 1]) <= 1))            return false;    }    else if (row == 1 && col == 3) {        if (UsedInGrid(grid, num)            || (abs(num - grid[row - 1][col - 1]) <= 1)            || (abs(num - grid[row][col - 1]) <= 1)            || (abs(num - grid[row + 1][col - 1]) <= 1))            return false;    }    else if (row == 2 && col == 1) {        if (UsedInGrid(grid, num)         || (abs(num - grid[row - 1][col - 1]) <= 1)         || (abs(num - grid[row - 1][col]) <= 1)         || (abs(num - grid[row - 1][col + 1]) <= 1)        || (abs(num - grid[row][col + 1]) <= 1))            return false;    }    else if (row == 2 && col == 2) {        if (UsedInGrid(grid, num)         || (abs(num - grid[row][col - 1]) <= 1)        || (abs(num - grid[row - 1][col]) <= 1)         || (abs(num - grid[row - 1][col + 1]) <= 1)         || (abs(num - grid[row - 1][col - 1]) <= 1))            return false;    }    else if (row == 1 && col == 1) {        if (UsedInGrid(grid, num)         || (abs(num - grid[row][col - 1]) <= 1)         || (abs(num - grid[row - 1][col]) <= 1)         || (abs(num - grid[row - 1][col + 1]) <= 1)         || (abs(num - grid[row][col + 1]) <= 1)        || (abs(num - grid[row + 1][col + 1]) <= 1)         || (abs(num - grid[row + 1][col]) <= 1))            return false;    }    else if (row == 1 && col == 2) {        if (UsedInGrid(grid, num)         || (abs(num - grid[row][col - 1]) <= 1)         || (abs(num - grid[row - 1][col]) <= 1)         || (abs(num - grid[row + 1][col - 1]) <= 1)         || (abs(num - grid[row][col + 1]) <= 1)         || (abs(num - grid[row - 1][col - 1]) <= 1)         || (abs(num - grid[row + 1][col]) <= 1))            return false;    }    return true;}Â
// This function finds an entry // in grid that is still unassignedbool FindUnassignedLocation(int grid[N][M],                        int& row, int& col){    for (row = 0; row < N; row++)        for (col = 0; col < M; col++) {            if (grid[row][col] == UNASSIGNED)                return true;        }    return false;}Â
/* A utility function to print grid */void printGrid(int grid[N][M]){    for (int i = 0; i < N; i++) {        if (i == 0 || i == N - 1)            cout << " ";        for (int j = 0; j < M; j++) {            if (grid[i][j] == 0)                cout << " ";            else                cout << grid[i][j] << " ";        }        cout << endl;    }}Â
/* Takes a grid and attempts to assign values toall unassigned locations in such a way to meet the requirements for this solution.*/bool Solve(int grid[N][M]){Â Â Â Â int row, col;Â
    // If there is no unassigned location, we are done    if (!FindUnassignedLocation(grid, row, col))        return true; // success!Â
    // consider digits 1 to 8    for (int num = 1; num <= 8; num++) {                 // if looks promising        if (isSafe(grid, row, col, num)) {                     // make tentative assignment            grid[row][col] = num;                     // return, if success, yay!            if (Solve(grid))                return true;                     // failure, unmake & try again            grid[row][col] = UNASSIGNED;        }    }    return false; // this triggers backtracking}Â
/* Driver Program to test above functions */int main(){    // -1 means unassigned cells    int grid[N][M] = { { 0, -1, -1, 0 },                    { -1, -1, -1, -1 },                    { 0, -1, -1, 0 } };                         if (Solve(grid) == true)        printGrid(grid);    else        cout << "Not possible";         return 0;} |
3 5 7 1 8 2 4 6
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

