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.
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.
Like all other Backtraking 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
3 5 7 1 8 2 4 6
- Fill two instances of all numbers from 1 to n in a specific way
- Count Magic squares in a grid
- Unique paths covering every non-obstacle block exactly once in a grid
- Why are negative numbers stored as 2's complement?
- Maximum of four numbers without using conditional or bitwise operator
- Find if a molecule can be formed from 3 atoms using their valence numbers
- Prime numbers after prime P with sum S
- Print a given matrix in spiral form using direction tracking method
- Program to generate all possible valid IP addresses from given string | Set 2
- Rat in a Maze Problem when movement in all possible directions is allowed
- Generate all permutations of a string that follow given constraints
- Travelling Salesman Problem implementation using BackTracking
- Find triplet such that number of nodes connecting these triplets is maximum
- Print path from root to all nodes in a Complete Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.