backtrackprob
backtrackprob
backtrackprob
The N Queen is the problem of placing N chess queens on an N×N chessboard so that no
two queens attack each other. Queen can attack horizontally, vertically and diagonaly.For
example, following are two solutions for 4 Queen Problem
https://www.geeksforgeeks.org/printing-solutions-n-queen-problem/?ref=lbp
2-K Battle Ship
You are given NxM matrix. You have K battle ships. You are also given 3 parameters for each of
the battle ship - rowAttack, columnAttack and diagonalAttack. Each telling how many cells in a
row/column/diagonal(on each direction) the ship can attack. Your task is find whether the ships
can be placed in the board such that no one attacks each other.
To shed more light on the attacks, say if the ship is placed at (5,5) and if it's column attack range
is 3, then it can attack any ship from (5,2) to (5,8).
Link https://stackoverflow.com/questions/23726791/variation-of-n-queens
3- A* Search Algorithm
To approximate the shortest path in real-life situations, like- in maps, games where there can
be many hindrances.
We can consider a 2D Grid having several obstacles and we start from a source cell (coloured
red below) to reach towards a goal cell (coloured green below)
Informally speaking, A* Search algorithms, unlike other traversal techniques, it has “brains”.
What it means is that it is really a smart algorithm which separates it from the other
conventional algorithms. This fact is cleared in detail in below sections.
And it is also worth mentioning that many games and web-based maps use this algorithm to
find the shortest path very efficiently (approximation).
https://www.geeksforgeeks.org/a-search-algorithm/
4- Hidato Puzzle
The rules are:
You are given a grid with some numbers placed in it. The other squares in the grid will be blank.
The grid is not necessarily rectangular.
The grid may have holes in it.
The grid is always connected.
The number “1” is always present, as is another number that is equal to the number of squares
in the grid. Other numbers are present so as to force the solution to be unique.
It may be assumed that the difference between numbers present on the grid is not greater than
lucky 13.
The aim is to place a natural number in each blank square so that in the sequence of numbered
squares from “1” upwards, each square is in the wp:Moore neighborhood of the squares
immediately before and after it in the sequence (except for the first and last squares, of course,
which only have one-sided constraints).
Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along
the path from first to last square in numerical order.
A square may only contain one number.
In a proper Hidato puzzle, the solution is unique.
Solution
https://rosettacode.org/wiki/Solve_a_Hidato_puzzle
5- Knight Tour Problem
the knight is placed on the first block of an empty board and, moving according to the rules of
chess, must visit each square exactly once.
Path followed by Knight to cover all the cells
Following is chessboard with 8 x 8 cells. Numbers in cells indicate move number of Knight.
https://www.geeksforgeeks.org/the-knights-tour-problem-backtracking-1/
6- Numberix Puzzle
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible
to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann
neighborhood). Published puzzles also tend not to have holes in the grid and may not always
indicate the end node. Two examples follow:
0 0 0 0 0 0 0 0 0
0 0 46 45 0 55 74 0 0
0 38 0 0 43 0 0 78 0
0 35 0 0 0 0 0 71 0
0 0 33 0 0 0 59 0 0
0 17 0 0 0 0 0 67 0
0 18 0 0 11 0 0 64 0
0 0 24 21 0 1 2 0 0
0 0 0 0 0 0 0 0 0
Solution
49 50 51 52 53 54 75 76 81
48 47 46 45 44 55 74 77 80
37 38 39 40 43 56 73 78 79
36 35 34 41 42 57 72 71 70
31 32 33 14 13 58 59 68 69
30 17 16 15 12 61 60 67 66
29 18 19 20 11 62 63 64 65
28 25 24 21 10 1 2 3 4
27 26 23 22 9 8 7 6 5
7- Magnet Puzzle
The puzzle game Magnets involves placing a set of domino-shaped magnets (or electrets or
other polarized objects) in a subset of slots on a M X N board so as to satisfy a set of
constraints. For example, the puzzle on the left has the solution shown on the right
Each slot contains either a blank entry (indicated by ‘x’s), or a “magnet” with a positive and
negative end. The numbers along the left and top sides show the numbers of ‘+’ squares in
particular rows or columns. Those along the right and bottom show the number of ‘-’ signs in
particular rows or columns. Rows and columns without a number at one or both ends are
unconstrained as to the number of ‘+’ or ‘-’ signs, depending on which number is not present. In
addition to fulfilling these numerical constraints, a puzzle solution must also satisfy the
constraint that no two orthogonally touching squares may have the same sign (diagonally
joined squares are not constrained).
You are given top[], bottom[], left[], right[] arrays indicates the count of + or – along the top(+),
bottom(-), left(+) and right(-) edges respectively. Values of -1 indicate any number of + and –
signs. Also given matrix rules[][] contain any one T, B, L or R characters. For a vertical slot in the
board, T indicates its top end and B indicates the bottom end. For a horizontal slot in the board,
L indicates left end and R indicates the right end.
input : M = 5, N = 6
top[] = { 1, -1, -1, 2, 1, -1 }
bottom[] = { 2, -1, -1, 2, -1, 3 }
left[] = { 2, 3, -1, -1, -1 }
right[] = { -1, -1, -1, 1, -1 }
rules[][] = { { L, R, L, R, T, T },
{ L, R, L, R, B, B },
{ T, T, T, T, L, R },
{ B, B, B, B, T, T },
{ L, R, L, R, B, B }};
Output : + - + - X -
-+-+X+
XX+-+-
XX-+X+
-+XXX-
Input : M = 4, N = 3
top[] = { 2, -1, -1 }
bottom[] = { -1, -1, 2 }
left[] = { -1, -1, 2, -1 }
right[] = { 0, -1, -1, -1 }
rules[][] = { { T, T, T },
{ B, B, B },
{ T, L, R },
{ B, L, R } };
Output : + X +
–X–
+–+
–+–
8- Rat In a Maze
A Maze is given as N*N binary matrix of blocks where source block is the upper left most block
i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts
from source and has to reach the destination. The rat can move only in two directions: forward
and down.
In the maze matrix, 0 means the block is a dead end and 1 means the block can be used in the
path from source to destination. Note that this is a simple version of the typical Maze problem.
For example, a more complex version can be that the rat can move in 4 directions and a more
complex version can be with a limited number of moves.
Solution
9- Print all shortest route in a grid
Given a matrix of N*M order. Find the shortest distance from a source cell to a destination cell,
traversing through limited cells only. Also you can move only up, down, left and right. If found
output the distance else -1. s represents ‘source’ d represents ‘destination’ * represents cell
you can travel 0 represents cell you can not travel This problem is meant for single source and
destination.
https://www.techiedelight.com/print-triplets-array-sum-less-equal-given-number/
11- Find total number of unique path in maze from source to destination
https://www.techiedelight.com/find-total-number-unique-paths-maze-source-destination/
12- Subset Sum Problem
Subset sum problem is to find subset of elements that are selected from a given set whose sum
adds up to a given number K. We are considering the set contains non-negative values. It is
assumed that the input set is unique (no duplicates are presented)
https://www.geeksforgeeks.org/subset-sum-backtracking-4/
length | 1 2 3 4 5 6 7 8
--------------------------------------------
price | 1 5 8 9 10 17 17 20
And if the prices are as following, then the maximum obtainable value is 24 (by cutting in eight
pieces of length 1)
length | 1 2 3 4 5 6 7 8
--------------------------------------------
price | 3 5 8 9 10 17 17 20
https://www.geeksforgeeks.org/cutting-a-rod-dp-13/
.
15- Print all triplets in an array with sum is less than or equal to given number
https://www.techiedelight.com/print-triplets-array-sum-less-equal-given-number/
17- find ways to calculate a target from array use addition and substraction
operator
https://www.techiedelight.com/find-ways-calculate-target-elements-array/
https://www.geeksforgeeks.org/printing-longest-common-subsequence/
Input : GEEKSFORGEEKS
Output : Output can be either EEKEE
or EESEE or EEGEE, ..
https://www.geeksforgeeks.org/construction-of-longest-increasing-subsequence-using-
dynamic-programming/
Input: "ilikesamsungmobile"
Output: i like sam sung mobile
i like samsung mobile
Input: "ilikeicecreamandmango"
Output: i like ice cream and man go
i like ice cream and mango
i like icecream and man go
i like icecream and mango
https://www.geeksforgeeks.org/word-break-problem-using-backtracking/?ref=lbp
Examples:
Input: str1 = "geek", str2 = "gesek"
Output: 1
We can convert str1 into str2 by inserting a 's'.
24- Edit Distance
Given two strings str1 and str2 and below operations that can performed on str1. Find
minimum number of edits (operations) required to convert ‘str1’ into ‘str2’.
1-Insert
2-Remove
All of the above operations are of equal cost.
Examples:
Input: str1 = "geek", str2 = "gesek"
Output: 1
We can convert str1 into str2 by inserting a 's'.
https://www.techiedelight.com/find-optimal-cost-to-construct-binary-search-tree/
26- Graph Coloring
Given an undirected graph and a number m, determine if the graph can be coloured with at
most m colours such that no two adjacent vertices of the graph are colored with the same
color. Here coloring of a graph means the assignment of colors to all vertices.
Input-Output format:
Input:
1. A 2D array graph[V][V] where V is the number of vertices in graph and graph[V][V] is
adjacency matrix representation of the graph. A value graph[i][j] is 1 if there is a direct
edge from i to j, otherwise graph[i][j] is 0.
2. An integer m which is the maximum number of colors that can be used.
Output:
An array color[V] that should have numbers from 1 to m. color[i] should represent the color
assigned to the ith vertex. The code should also return false if the graph cannot be colored with
m colors.
Example:
Input:
graph = {0, 1, 1, 1},
{1, 0, 1, 0},
{1, 1, 0, 1},
{1, 0, 1, 0}
Output:
Solution Exists:
Following are the assigned colors
1 2 3 2
Explanation: By coloring the vertices
with following colors, adjacent
vertices does not have same colors
https://www.geeksforgeeks.org/m-coloring-problem-backtracking-5/