Open In App

Fill 8 numbers in grid with given conditions

Improve
Improve
Like Article
Like
Save
Share
Report

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 -1
using namespace std;
 
/* Returns a boolean which indicates
whether any assigned entry within the
specified 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 indicates
whether it will be legal to assign
num 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 unassigned
bool 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 to
all 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;
}


Output: 

  3 5  
7 1 8 2 
  4 6

 



Last Updated : 07 Jul, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads