The Knight’s tour problem
Last Updated :
17 Apr, 2024
Backtracking is an algorithmic paradigm that tries different solutions until finds a solution that “works”. Problems that are typically solved using the backtracking technique have the following property in common. These problems can only be solved by trying every possible configuration and each configuration is tried only once. A Naive solution for these problems is to try all configurations and output a configuration that follows given problem constraints. Backtracking works incrementally and is an optimization over the Naive solution where all possible configurations are generated and tried.
For example, consider the following Knight’s Tour problem.Â
Problem Statement:
Given a N*N board with the Knight placed on the first block of an empty board. Moving according to the rules of chess knight must visit each square exactly once. Print the order of each cell in which they are visited.
Example:
Input :
N = 8
Output:
0 59 38 33 30 17 8 63
37 34 31 60 9 62 29 16
58 1 36 39 32 27 18 7
35 48 41 26 61 10 15 28
42 57 2 49 40 23 6 19
47 50 45 54 25 20 11 14
56 43 52 3 22 13 24 5
51 46 55 44 53 4 21 12
The path followed by Knight to cover all the cells
Following is a chessboard with 8 x 8 cells. Numbers in cells indicate the move number of Knight.Â

Let us first discuss the Naive algorithm for this problem and then the Backtracking algorithm.
Naive Algorithm for Knight’s tourÂ
The Naive Algorithm is to generate all tours one by one and check if the generated tour satisfies the constraints.Â
while there are untried tours
{
generate the next tour
if this tour covers all squares
{
print this path;
}
}
Backtracking works in an incremental way to attack problems. Typically, we start from an empty solution vector and one by one add items (Meaning of item varies from problem to problem. In the context of Knight’s tour problem, an item is a Knight’s move). When we add an item, we check if adding the current item violates the problem constraint, if it does then we remove the item and try other alternatives. If none of the alternatives works out then we go to the previous stage and remove the item added in the previous stage. If we reach the initial stage back then we say that no solution exists. If adding an item doesn’t violate constraints then we recursively add items one by one. If the solution vector becomes complete then we print the solution.
Backtracking Algorithm for Knight’s tourÂ
Following is the Backtracking algorithm for Knight’s tour problem.Â
If all squares are visited
print the solution
Else
a) Add one of the next moves to solution vector and recursively
check if this move leads to a solution. (A Knight can make maximum
eight moves. We choose one of the 8 moves in this step).
b) If the move chosen in the above step doesn't lead to a solution
then remove this move from the solution vector and try other
alternative moves.
c) If none of the alternatives work then return false (Returning false
will remove the previously added item in recursion and if false is
returned by the initial call of recursion then "no solution exists" )
Following are implementations for Knight’s tour problem. It prints one of the possible solutions in 2D matrix form. Basically, the output is a 2D 8*8 matrix with numbers from 0 to 63 and these numbers show steps made by Knight.Â
Â
C++
// C++ program for Knight Tour problem
#include <bits/stdc++.h>
using namespace std;
#define N 8
int solveKTUtil(int x, int y, int movei, int sol[N][N],
int xMove[], int yMove[]);
/* A utility function to check if i,j are
valid indexes for N*N chessboard */
int isSafe(int x, int y, int sol[N][N])
{
return (x >= 0 && x < N && y >= 0 && y < N
&& sol[x][y] == -1);
}
/* A utility function to print
solution matrix sol[N][N] */
void printSolution(int sol[N][N])
{
for (int x = 0; x < N; x++) {
for (int y = 0; y < N; y++)
cout << " " << setw(2) << sol[x][y] << " ";
cout << endl;
}
}
/* This function solves the Knight Tour problem using
Backtracking. This function mainly uses solveKTUtil()
to solve the problem. It returns false if no complete
tour is possible, otherwise return true and prints the
tour.
Please note that there may be more than one solutions,
this function prints one of the feasible solutions. */
int solveKT()
{
int sol[N][N];
/* Initialization of solution matrix */
for (int x = 0; x < N; x++)
for (int y = 0; y < N; y++)
sol[x][y] = -1;
/* xMove[] and yMove[] define next move of Knight.
xMove[] is for next value of x coordinate
yMove[] is for next value of y coordinate */
int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 };
int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };
// Since the Knight is initially at the first block
sol[0][0] = 0;
/* Start from 0,0 and explore all tours using
solveKTUtil() */
if (solveKTUtil(0, 0, 1, sol, xMove, yMove) == 0) {
cout << "Solution does not exist";
return 0;
}
else
printSolution(sol);
return 1;
}
/* A recursive utility function to solve Knight Tour
problem */
int solveKTUtil(int x, int y, int movei, int sol[N][N],
int xMove[8], int yMove[8])
{
int k, next_x, next_y;
if (movei == N * N)
return 1;
/* Try all next moves from
the current coordinate x, y */
for (k = 0; k < 8; k++) {
next_x = x + xMove[k];
next_y = y + yMove[k];
if (isSafe(next_x, next_y, sol)) {
sol[next_x][next_y] = movei;
if (solveKTUtil(next_x, next_y, movei + 1, sol,
xMove, yMove)
== 1)
return 1;
else
// backtracking
sol[next_x][next_y] = -1;
}
}
return 0;
}
// Driver Code
int main()
{
// Function Call
solveKT();
return 0;
}
// This code is contributed by ShubhamCoder
C
// C program for Knight Tour problem
#include <stdio.h>
#define N 8
int solveKTUtil(int x, int y, int movei, int sol[N][N],
int xMove[], int yMove[]);
/* A utility function to check if i,j are valid indexes
for N*N chessboard */
int isSafe(int x, int y, int sol[N][N])
{
return (x >= 0 && x < N && y >= 0 && y < N
&& sol[x][y] == -1);
}
/* A utility function to print solution matrix sol[N][N] */
void printSolution(int sol[N][N])
{
for (int x = 0; x < N; x++) {
for (int y = 0; y < N; y++)
printf(" %2d ", sol[x][y]);
printf("\n");
}
}
/* This function solves the Knight Tour problem using
Backtracking. This function mainly uses solveKTUtil()
to solve the problem. It returns false if no complete
tour is possible, otherwise return true and prints the
tour.
Please note that there may be more than one solutions,
this function prints one of the feasible solutions. */
int solveKT()
{
int sol[N][N];
/* Initialization of solution matrix */
for (int x = 0; x < N; x++)
for (int y = 0; y < N; y++)
sol[x][y] = -1;
/* xMove[] and yMove[] define next move of Knight.
xMove[] is for next value of x coordinate
yMove[] is for next value of y coordinate */
int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 };
int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };
// Since the Knight is initially at the first block
sol[0][0] = 0;
/* Start from 0,0 and explore all tours using
solveKTUtil() */
if (solveKTUtil(0, 0, 1, sol, xMove, yMove) == 0) {
printf("Solution does not exist");
return 0;
}
else
printSolution(sol);
return 1;
}
/* A recursive utility function to solve Knight Tour
problem */
int solveKTUtil(int x, int y, int movei, int sol[N][N],
int xMove[N], int yMove[N])
{
int k, next_x, next_y;
if (movei == N * N)
return 1;
/* Try all next moves from the current coordinate x, y
*/
for (k = 0; k < 8; k++) {
next_x = x + xMove[k];
next_y = y + yMove[k];
if (isSafe(next_x, next_y, sol)) {
sol[next_x][next_y] = movei;
if (solveKTUtil(next_x, next_y, movei + 1, sol,
xMove, yMove)
== 1)
return 1;
else
sol[next_x][next_y] = -1; // backtracking
}
}
return 0;
}
/* Driver Code */
int main()
{
// Function Call
solveKT();
return 0;
}
Java
// Java program for Knight Tour problem
class KnightTour {
static int N = 8;
/* A utility function to check if i,j are
valid indexes for N*N chessboard */
static boolean isSafe(int x, int y, int sol[][])
{
return (x >= 0 && x < N && y >= 0 && y < N
&& sol[x][y] == -1);
}
/* A utility function to print solution
matrix sol[N][N] */
static void printSolution(int sol[][])
{
for (int x = 0; x < N; x++) {
for (int y = 0; y < N; y++)
System.out.print(sol[x][y] + " ");
System.out.println();
}
}
/* This function solves the Knight Tour problem
using Backtracking. This function mainly
uses solveKTUtil() to solve the problem. It
returns false if no complete tour is possible,
otherwise return true and prints the tour.
Please note that there may be more than one
solutions, this function prints one of the
feasible solutions. */
static boolean solveKT()
{
int sol[][] = new int[8][8];
/* Initialization of solution matrix */
for (int x = 0; x < N; x++)
for (int y = 0; y < N; y++)
sol[x][y] = -1;
/* xMove[] and yMove[] define next move of Knight.
xMove[] is for next value of x coordinate
yMove[] is for next value of y coordinate */
int xMove[] = { 2, 1, -1, -2, -2, -1, 1, 2 };
int yMove[] = { 1, 2, 2, 1, -1, -2, -2, -1 };
// Since the Knight is initially at the first block
sol[0][0] = 0;
/* Start from 0,0 and explore all tours using
solveKTUtil() */
if (!solveKTUtil(0, 0, 1, sol, xMove, yMove)) {
System.out.println("Solution does not exist");
return false;
}
else
printSolution(sol);
return true;
}
/* A recursive utility function to solve Knight
Tour problem */
static boolean solveKTUtil(int x, int y, int movei,
int sol[][], int xMove[],
int yMove[])
{
int k, next_x, next_y;
if (movei == N * N)
return true;
/* Try all next moves from the current coordinate
x, y */
for (k = 0; k < 8; k++) {
next_x = x + xMove[k];
next_y = y + yMove[k];
if (isSafe(next_x, next_y, sol)) {
sol[next_x][next_y] = movei;
if (solveKTUtil(next_x, next_y, movei + 1,
sol, xMove, yMove))
return true;
else
sol[next_x][next_y]
= -1; // backtracking
}
}
return false;
}
/* Driver Code */
public static void main(String args[])
{
// Function Call
solveKT();
}
}
// This code is contributed by Abhishek Shankhadhar
Python3
# Python3 program to solve Knight Tour problem using Backtracking
# Chessboard Size
n = 8
def isSafe(x, y, board):
'''
A utility function to check if i,j are valid indexes
for N*N chessboard
'''
if(x >= 0 and y >= 0 and x < n and y < n and board[x][y] == -1):
return True
return False
def printSolution(n, board):
'''
A utility function to print Chessboard matrix
'''
for i in range(n):
for j in range(n):
print(board[i][j], end=' ')
print()
def solveKT(n):
'''
This function solves the Knight Tour problem using
Backtracking. This function mainly uses solveKTUtil()
to solve the problem. It returns false if no complete
tour is possible, otherwise return true and prints the
tour.
Please note that there may be more than one solutions,
this function prints one of the feasible solutions.
'''
# Initialization of Board matrix
board = [[-1 for i in range(n)]for i in range(n)]
# move_x and move_y define next move of Knight.
# move_x is for next value of x coordinate
# move_y is for next value of y coordinate
move_x = [2, 1, -1, -2, -2, -1, 1, 2]
move_y = [1, 2, 2, 1, -1, -2, -2, -1]
# Since the Knight is initially at the first block
board[0][0] = 0
# Step counter for knight's position
pos = 1
# Checking if solution exists or not
if(not solveKTUtil(n, board, 0, 0, move_x, move_y, pos)):
print("Solution does not exist")
else:
printSolution(n, board)
def solveKTUtil(n, board, curr_x, curr_y, move_x, move_y, pos):
'''
A recursive utility function to solve Knight Tour
problem
'''
if(pos == n**2):
return True
# Try all next moves from the current coordinate x, y
for i in range(8):
new_x = curr_x + move_x[i]
new_y = curr_y + move_y[i]
if(isSafe(new_x, new_y, board)):
board[new_x][new_y] = pos
if(solveKTUtil(n, board, new_x, new_y, move_x, move_y, pos+1)):
return True
# Backtracking
board[new_x][new_y] = -1
return False
# Driver Code
if __name__ == "__main__":
# Function Call
solveKT(n)
# This code is contributed by AAKASH PAL
C#
// C# program for
// Knight Tour problem
using System;
class GFG {
static int N = 8;
/* A utility function to
check if i,j are valid
indexes for N*N chessboard */
static bool isSafe(int x, int y, int[, ] sol)
{
return (x >= 0 && x < N && y >= 0 && y < N
&& sol[x, y] == -1);
}
/* A utility function to
print solution matrix sol[N][N] */
static void printSolution(int[, ] sol)
{
for (int x = 0; x < N; x++) {
for (int y = 0; y < N; y++)
Console.Write(sol[x, y] + " ");
Console.WriteLine();
}
}
/* This function solves the
Knight Tour problem using
Backtracking. This function
mainly uses solveKTUtil() to
solve the problem. It returns
false if no complete tour is
possible, otherwise return true
and prints the tour. Please note
that there may be more than one
solutions, this function prints
one of the feasible solutions. */
static bool solveKT()
{
int[, ] sol = new int[8, 8];
/* Initialization of
solution matrix */
for (int x = 0; x < N; x++)
for (int y = 0; y < N; y++)
sol[x, y] = -1;
/* xMove[] and yMove[] define
next move of Knight.
xMove[] is for next
value of x coordinate
yMove[] is for next
value of y coordinate */
int[] xMove = { 2, 1, -1, -2, -2, -1, 1, 2 };
int[] yMove = { 1, 2, 2, 1, -1, -2, -2, -1 };
// Since the Knight is
// initially at the first block
sol[0, 0] = 0;
/* Start from 0,0 and explore
all tours using solveKTUtil() */
if (!solveKTUtil(0, 0, 1, sol, xMove, yMove)) {
Console.WriteLine("Solution does "
+ "not exist");
return false;
}
else
printSolution(sol);
return true;
}
/* A recursive utility function
to solve Knight Tour problem */
static bool solveKTUtil(int x, int y, int movei,
int[, ] sol, int[] xMove,
int[] yMove)
{
int k, next_x, next_y;
if (movei == N * N)
return true;
/* Try all next moves from
the current coordinate x, y */
for (k = 0; k < 8; k++) {
next_x = x + xMove[k];
next_y = y + yMove[k];
if (isSafe(next_x, next_y, sol)) {
sol[next_x, next_y] = movei;
if (solveKTUtil(next_x, next_y, movei + 1,
sol, xMove, yMove))
return true;
else
// backtracking
sol[next_x, next_y] = -1;
}
}
return false;
}
// Driver Code
public static void Main()
{
// Function Call
solveKT();
}
}
// This code is contributed by mits.
JavaScript
<script>
// Javascript program for Knight Tour problem
let N = 8;
// A utility function to check if i,j are
// valid indexes for N*N chessboard
function isSafe(x, y, sol)
{
return(x >= 0 && x < N && y >= 0 &&
y < N && sol[x][y] == -1);
}
// A utility function to print solution
// matrix sol[N][N]
function printSolution(sol)
{
for(let x = 0; x < N; x++)
{
for(let y = 0; y < N; y++)
document.write(sol[x][y] + " ");
document.write("<br/>");
}
}
// This function solves the Knight Tour problem
// using Backtracking. This function mainly
// uses solveKTUtil() to solve the problem. It
// returns false if no complete tour is possible,
// otherwise return true and prints the tour.
// Please note that there may be more than one
// solutions, this function prints one of the
// feasible solutions.
function solveKT()
{
let sol = new Array(N);
for(var i = 0; i < sol.length; i++)
{
sol[i] = new Array(N);
}
// Initialization of solution matrix
for(let x = 0; x < N; x++)
for(let y = 0; y < N; y++)
sol[x][y] = -1;
// xMove[] and yMove[] define next move of Knight.
// xMove[] is for next value of x coordinate
// yMove[] is for next value of y coordinate
let xMove = [ 2, 1, -1, -2, -2, -1, 1, 2 ];
let yMove = [ 1, 2, 2, 1, -1, -2, -2, -1 ];
// Since the Knight is initially at the first block
sol[0][0] = 0;
// Start from 0,0 and explore all tours using
// solveKTUtil()
if (!solveKTUtil(0, 0, 1, sol, xMove, yMove))
{
document.write("Solution does not exist");
return false;
}
else
printSolution(sol);
return true;
}
// A recursive utility function to solve Knight
// Tour problem
function solveKTUtil(x, y, movei, sol, xMove, yMove)
{
let k, next_x, next_y;
if (movei == N * N)
return true;
// Try all next moves from the
// current coordinate x, y
for(k = 0; k < 8; k++)
{
next_x = x + xMove[k];
next_y = y + yMove[k];
if (isSafe(next_x, next_y, sol))
{
sol[next_x][next_y] = movei;
if (solveKTUtil(next_x, next_y, movei + 1,
sol, xMove, yMove))
return true;
else
sol[next_x][next_y] = -1; // backtracking
}
}
return false;
}
// Driver code
// Function Call
solveKT();
// This code is contributed by target_2
</script>
Output 0 59 38 33 30 17 8 63
37 34 31 60 9 62 29 16
58 1 36 39 32 27 18 7
35 48 41 26 61 10 15 28
42 57 2 49 40 23 6 19
47 50 45 54 25 20 11 14
56 43 52 3 22 13 24 5
51 46 55 44 53 4 21 12
Time Complexity :Â
There are N2 Cells and for each, we have a maximum of 8 possible moves to choose from, so the worst running time is O(8N^2).
Auxiliary Space: O(N2)
Important Note:
No order of the xMove, yMove is wrong, but they will affect the running time of the algorithm drastically. For example, think of the case where the 8th choice of the move is the correct one, and before that our code ran 7 different wrong paths. It’s always a good idea a have a heuristic than to try backtracking randomly. Like, in this case, we know the next step would probably be in the south or east direction, then checking the paths which lead their first is a better strategy.
Note that Backtracking is not the best solution for the Knight’s tour problem. See the below article for other better solutions. The purpose of this post is to explain Backtracking with an example.Â
Warnsdorffâs algorithm for Knightâs tour problem
References:Â
http://see.stanford.edu/materials/icspacs106b/H19-RecBacktrackExamples.pdfÂ
http://www.cis.upenn.edu/~matuszek/cit594-2009/Lectures/35-backtracking.pptÂ
http://mathworld.wolfram.com/KnightsTour.htmlÂ
http://en.wikipedia.org/wiki/Knight%27s_tourÂ
Â
Similar Reads
Backtracking Algorithm
Backtracking algorithms are like problem-solving strategies that help explore different options to find the best solution. They work by trying out different paths and if one doesn't work, they backtrack and try another until they find the right one. It's like solving a puzzle by testing different pi
4 min read
Introduction to Backtracking
Backtracking is like trying different paths, and when you hit a dead end, you backtrack to the last choice and try a different route. In this article, we'll explore the basics of backtracking, how it works, and how it can help solve all sorts of challenging problems. It's like a method for finding t
7 min read
Difference between Backtracking and Branch-N-Bound technique
Algorithms are the methodical sequence of steps which are defined to solve complex problems. In this article, we will see the difference between two such algorithms which are backtracking and branch and bound technique. Before getting into the differences, lets first understand each of these algorit
4 min read
What is the difference between Backtracking and Recursion?
What is Recursion? The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Properties of Recursion:Performing the same operations multiple times with different inputs.In every step, we try smaller inputs t
2 min read
Standard problems on backtracking
The Knight's tour problem
Backtracking is an algorithmic paradigm that tries different solutions until finds a solution that "works". Problems that are typically solved using the backtracking technique have the following property in common. These problems can only be solved by trying every possible configuration and each con
15+ min read
Rat in a Maze
We have discussed Backtracking and Knight's tour problem in Set 1. Let us discuss Rat in a Maze as another example problem that can be solved using Backtracking. Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible pa
11 min read
N Queen Problem
We have discussed Knightâs tour and Rat in a Maze problem earlier as examples of Backtracking problems. Let us discuss N Queen as another example problem that can be solved using backtracking. What is N-Queen problem?The N Queen is the problem of placing N chess queens on an NÃN chessboard so that n
15+ min read
Subset Sum Problem using Backtracking
Given a set[] of non-negative integers and a value sum, the task is to print the subset of the given set whose sum is equal to the given sum. Examples:Â Input:Â set[] = {1,2,1}, sum = 3Output:Â [1,2],[2,1]Explanation:Â There are subsets [1,2],[2,1] with sum 3. Input:Â set[] = {3, 34, 4, 12, 5, 2}, sum =
8 min read
M-Coloring Problem
Given an undirected graph and a number m, the task is to color the given graph with at most m colors such that no two adjacent vertices of the graph are colored with the same color Note: Here coloring of a graph means the assignment of colors to all vertices Below is an example of a graph that can b
15+ min read
Hamiltonian Cycle
What is Hamiltonian Cycle?Hamiltonian Cycle or Circuit in a graph G is a cycle that visits every vertex of G exactly once and returns to the starting vertex. If graph contains a Hamiltonian cycle, it is called Hamiltonian graph otherwise it is non-Hamiltonian.Finding a Hamiltonian Cycle in a graph i
15+ min read
Algorithm to Solve Sudoku | Sudoku Solver
Given an incomplete Sudoku in the form of matrix mat[][] of order 9*9, the task is to complete the Sudoku.A sudoku solution must satisfy all of the following rules: Each of the digits 1-9 must occur exactly once in each row.Each of the digits 1-9 must occur exactly once in each column.Each of the di
15+ min read
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 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
15+ min read
Remove Invalid Parentheses
An expression will be given which can contain open and close parentheses and optionally some characters, No other operator will be there in string. We need to remove minimum number of parentheses to make the input string valid. If more than one valid output are possible removing same number of paren
9 min read
A backtracking approach to generate n bit Gray Codes
Given a number n, the task is to generate n bit Gray codes (generate bit patterns from 0 to 2^n-1 such that successive patterns differ by one bit) Examples: Input : 2 Output : 0 1 3 2Explanation : 00 - 001 - 111 - 310 - 2Input : 3 Output : 0 1 3 2 6 7 5 4 We have discussed an approach in Generate n-
6 min read
Permutations of given String
Given a string s, the task is to return all permutations of a given string in lexicographically sorted order. Note: A permutation is the rearrangement of all the elements of a string. Duplicate arrangement can exist. Examples: Input: s = "ABC"Output: "ABC", "ACB", "BAC", "BCA", "CBA", "CAB" Input: s
5 min read
Easy Problems on Backtracking
Print all subsets of a given Set or Array
Given an array Arr[] of size N, print all the subsets of the array. Subset: A subset of an array is a tuple that can be obtained from the array by removing some (possibly all) elements of it Example: Input: N = 3, Arr = [1, 2, 3]Output: {} {1} {1, 2} {1, 2, 3} {1, 3} {2} {2, 3} {3}Explanation: These
11 min read
Check if a given string is sum-string
Given a string of digits, determine whether it is a âsum-stringâ. A string S is called a sum-string if the rightmost substring can be written as the sum of two substrings before it and the same is recursively true for substrings before it. Examples: â12243660â is a sum string. Explanation : 24 + 36
12 min read
Count all possible Paths between two Vertices
Count the total number of ways or paths that exist between two vertices in a directed graph. These paths don't contain a cycle, the simple enough reason is that a cycle contains an infinite number of paths and hence they create a problem Examples: For the following Graph: Input: Count paths between
9 min read
Find all distinct subsets of a given set using BitMasking Approach
Given an array of integers arr[], The task is to find all its subsets. The subset can not contain duplicate elements, so any repeated subset should be considered only once in the output. Examples: Input: S = {1, 2, 2}Output: {}, {1}, {2}, {1, 2}, {2, 2}, {1, 2, 2}Explanation: The total subsets of gi
12 min read
Find if there is a path of more than k length from a source
Given a graph, a source vertex in the graph and a number k, find if there is a simple path (without any cycle) starting from given source and ending at any other vertex such that the distance from source to that vertex is atleast 'k' length. Example: Input : Source s = 0, k = 58 Output : True There
15 min read
Print all paths from a given source to a destination
Given a directed graph, a source vertex 's' and a destination vertex 'd', print all paths from given 's' to 'd'. Consider the following directed graph. Let the s be 2 and d be 3. There are 3 different paths from 2 to 3. Recommended PracticeCount the pathsTry It!Approach: The idea is to do Depth Fir
10 min read
Print all possible strings that can be made by placing spaces
Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them. Input: str[] = "ABC" Output: ABC AB C A BC A B C Source: Amazon Interview Experience | Set 158, Round 1, Q 1. Recommended PracticePermutation with SpacesTry It! The idea is to use
11 min read
Medium prblems on Backtracking
Tug of War
Given a set of n integers, divide the set in two subsets of n/2 sizes each such that the absolute difference of the sum of two subsets is as minimum as possible. If n is even, then sizes of two subsets must be strictly n/2 and if n is odd, then size of one subset must be (n-1)/2 and size of other su
15 min read
8 queen problem
The eight queens problem is the problem of placing eight queens on an 8Ã8 chessboard such that none of them attack one another (no two are in the same row, column, or diagonal). More generally, the n queens problem places n queens on an nÃn chessboard. There are different solutions for the problem.
8 min read
Combination Sum
Given an array of distinct integers arr[] and an integer target, the task is to find a list of all unique combinations of array where the sum of chosen element is equal to target. Note: The same number may be chosen from array an unlimited number of times. Two combinations are unique if the frequenc
8 min read
Warnsdorff's algorithm for Knightâs tour problem
Problem : A 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. Following is an example path followed by Knight to cover all the cells. The below grid represents a chessboard with 8 x 8 cells. Numbers in cells indica
15+ min read
Find paths from corner cell to middle cell in maze
Given a square maze containing positive numbers, find all paths from a corner cell (any of the extreme four corners) to the middle cell. We can move exactly n steps from a cell in 4 directions i.e. North, East, West and South where n is value of the cell, We can move to mat[i+n][j], mat[i-n][j], mat
15+ min read
Find Maximum number possible by doing at-most K swaps
Given a string s and an integer k, the task is to find the maximum possible number by performing swap operations on the digits of s at most k times. Examples: Input: s = "7599", k = 2Output: 9975Explanation: Swap 9 with 5 so number becomes 7995, Swap 9 with 7 so number becomes 9975 Input: s = "76543
15 min read
Rat in a Maze with multiple steps or jump allowed
This is the variation of Rat in 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 destination. The rat can move only in tw
13 min read
N Queen in O(n) space
Given n, of a n x n chessboard, find the proper placement of queens on chessboard.Previous Approach : N Queen Algorithm : Place(k, i) // Returns true if a queen can be placed // in kth row and ith column. Otherwise it // returns false. X[] is a global array // whose first (k-1) values have been set.
7 min read
Hard problems on Backtracking
Power Set in Lexicographic order
This article is about generating Power set in lexicographical order. Examples : Input : abcOutput : a ab abc ac b bc cThe idea is to sort array first. After sorting, one by one fix characters and recursively generates all subsets starting from them. After every recursive call, we remove last charact
9 min read
Word Break Problem using Backtracking
Given a non-empty sequence s and a dictionary dict[] containing a list of non-empty words, the task is to return all possible ways to break the sentence in individual dictionary words.Note: The same word in the dictionary may be reused multiple times while breaking.Examples: Input: s = âcatsanddogâ
8 min read
Partition of a set into K subsets with equal sum
Given an integer array arr[] and an integer k, the task is to check if it is possible to divide the given array into k non-empty subsets of equal sum such that every array element is part of a single subset. Examples: Input: arr[] = [2, 1, 4, 5, 6], k = 3 Output: trueExplanation: Possible subsets of
9 min read
Longest Possible Route in a Matrix with Hurdles
Given an M x N matrix, with a few hurdles arbitrarily placed, calculate the length of the longest possible route possible from source to a destination within the matrix. We are allowed to move to only adjacent cells which are not hurdles. The route cannot contain any diagonal moves and a location on
15+ min read
Find shortest safe route in a path with landmines
Given a path in the form of a rectangular matrix having few landmines arbitrarily placed (marked as 0), calculate length of the shortest safe route possible from any cell in the first column to any cell in the last column of the matrix. We have to avoid landmines and their four adjacent cells (left,
15+ min read
Printing all solutions in N-Queen Problem
Given an integer n, the task is to find all distinct solutions to the n-queens problem, where n queens are placed on an nÃn chessboard such that no two queens can attack each other. Each solution is a unique configuration of n queens, represented as a permutation of [1,2,3,....,n]. The number at the
15 min read
Print all longest common sub-sequences in lexicographical order
You are given two strings, the task is to print all the longest common sub-sequences in lexicographical order. Examples: Input : str1 = "abcabcaa", str2 = "acbacba" Output: ababa abaca abcba acaba acaca acbaa acbcaRecommended PracticePrint all LCS sequencesTry It! This problem is an extension of lon
14 min read
Top 20 Backtracking Algorithm Interview Questions
N Queens ProblemWarnsdorff's AlgorithmWord Break ProblemRemove Invalid ParenthesisMatch a pattern and string using regular expressionFind Path from corner cell to middle cell in a mazeHamiltonian cycleSudokuM Coloring ProblemRat in a MazePrint all permutations of a given stringCrptarithmetic puzzleF
1 min read