BackTracking Article GFG
BackTracking Article GFG
Concept of Backtracking
Rat in a Maze
Let us discuss Rat in a Maze as another example problem that can be solved using
Backtracking.
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.
{1, 0, 0, 0}
{1, 1, 0, 1}
{0, 1, 0, 0}
{1, 1, 1, 1}
Following is the solution matrix (output of program) for the above input matrix.
{1, 0, 0, 0}
{1, 1, 0, 0}
{0, 1, 0, 0}
{0, 1, 1, 1}
All entries in solution path are marked as 1.
Approach: Form a recursive function, which will follow a path and check if the path reaches
the destination or not. If the path does not reach the destination then backtrack and try
other paths.
Algorithm:
import java.util.*;
import java.io.*;
import java.lang.*;
class Gfg
static int N;
System.out.println();
return false;
printSolution(sol);
return true;
sol[i][j] = 1;
return true;
if (isSafe(maze, i, j) == true) {
sol[i][j] = 1;
if (solveMazeRec(maze, i + 1, j, sol))
return true;
if (solveMazeRec(maze, i, j + 1, sol))
return true;
sol[i][j] = 0;
}
return false;
int maze[][] = { { 1, 0, 0, 0 },
{ 1, 1, 0, 1 },
{ 0, 1, 0, 0 },
{ 1, 1, 1, 1 } };
N = maze.length;
solveMaze(maze);
Output:
1 0 0 0
1 1 0 0
0 1 0 0
0 1 1 1
Complexity Analysis:
N-Queen Problem
Let us discuss N Queen as another example problem that can be solved using backtracking.
The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two
queens attack each other. For example, the following is a solution for the 4 Queen problem.
The expected output is a binary matrix that has 1s for the blocks where queens are placed.
For example, the following is the output matrix for the above 4 queen solution.
{ 0, 1, 0, 0}
{ 0, 0, 0, 1}
{ 1, 0, 0, 0}
{ 0, 0, 1, 0}
Naive Algorithm
Generate all possible configurations of queens on board and print a configuration that
satisfies the given constraints.
Backtracking Algorithm
The idea is to place queens one by one in different columns, starting from the leftmost
column. When we place a queen in a column, we check for clashes with already placed
queens. In the current column, if we find a row for which there is no clash, we mark this row
and column as part of the solution. If we do not find such a row due to clashes, then we
backtrack and return false.
return true
C++Java
import java.util.*;
import java.io.*;
import java.lang.*;
class Gfg
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };
+ " ");
System.out.println();
int i, j;
if (board[row][i] == 1)
return false;
if (board[i][j] == 1)
return false;
if (board[i][j] == 1)
return false;
return true;
}
static boolean solveRec(int col)
if (col == N)
return true;
if (isSafe(i, col)) {
board[i][col] = 1;
if (solveRec(col + 1) == true)
return true;
board[i][col] = 0;
return false;
if (solveRec(0) == false) {
return false;
}
printSolution(board);
return true;
solve();
Output:
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
Sudoku Problem
Given a partially filled 9x9 2D array 'grid[9][9]', the goal is to assign digits (from 1 to 9) to the
empty cells so that every row, column, and subgrid of size 3x3 contains exactly one instance
of the digits from 1 to 9.
Example:
Input:
grid = { {3, 0, 6, 5, 0, 8, 4, 0, 0},
{5, 2, 0, 0, 0, 0, 0, 0, 0},
{0, 8, 7, 0, 0, 0, 0, 3, 1},
{0, 0, 3, 0, 1, 0, 0, 8, 0},
{9, 0, 0, 8, 6, 3, 0, 0, 5},
{0, 5, 0, 0, 9, 0, 6, 0, 0},
{1, 3, 0, 0, 0, 0, 2, 5, 0},
{0, 0, 0, 0, 0, 0, 0, 7, 4},
{0, 0, 5, 2, 0, 6, 3, 0, 0} }
Output:
316578492
529134768
487629531
263415987
974863125
851792643
138947256
692351874
745286319
Explanation: Each row, column and 3*3 box of
the output matrix contains unique numbers.
Input:
grid = { { 3, 1, 6, 5, 7, 8, 4, 9, 2 },
{ 5, 2, 9, 1, 3, 4, 7, 6, 8 },
{ 4, 8, 7, 6, 2, 9, 5, 3, 1 },
{ 2, 6, 3, 0, 1, 5, 9, 8, 7 },
{ 9, 7, 4, 8, 6, 0, 1, 2, 5 },
{ 8, 5, 1, 7, 9, 2, 6, 4, 3 },
{ 1, 3, 8, 0, 4, 7, 2, 0, 6 },
{ 6, 9, 2, 3, 5, 1, 8, 7, 4 },
{ 7, 4, 5, 0, 8, 6, 3, 1, 0 } };
Output:
316578492
529134768
487629531
263415987
974863125
851792643
138947256
692351874
745286319
Explanation: Each row, column and 3*3 box of
the output matrix contains unique numbers.
Method 1: Simple.
Approach: The naive approach is to generate all possible configurations of numbers from 1 to
9 to fill the empty cells. Try every configuration one by one until the correct configuration is
found, i.e. for every unassigned position fill the position with a number from 1 to 9. After
filling all the unassigned position check if the matrix is safe or not. If safe print else recurs for
other cases.
Algorithm:
1. Create a function that checks if the given matrix is valid sudoku or not. Keep Hashmap for
the row, column and boxes. If any number has a frequency greater than 1 in the hashMap
return false else return true;
2. Create a recursive function that takes a grid and the current row and column index.
3. Check some base cases. If the index is at the end of the matrix, i.e. i=N-1 and j=N then
check if the grid is safe or not, if safe print the grid and return true else return false. The
other base case is when the value of column is N, i.e j = N, then move to next row, i.e. i++
and j = 0.
4. if the current index is not assigned then fill the element from 1 to 9 and recur for all 9
cases with the index of next element, i.e. i, j+1. if the recursive call returns true then break
the loop and return true.
5. if the current index is assigned then call the recursive function with index of next
element, i.e. i, j+1
Implementation:
C++Java
static int N = 9;
int col)
{
/*if we have reached the 8th
indexed matrix) ,
backtracking */
return true;
if (col == N) {
row++;
col = 0;
if (grid[row][col] != 0)
is correct */
grid[row][col] = num;
return true;
grid[row][col] = 0;
return false;
System.out.println();
int num)
// return false
if (grid[row][x] == num)
return false;
// we return false
if (grid[x][col] == num)
return false;
// Check if we find the same num
= col - col % 3;
return false;
return true;
// Driver Code
int grid[][] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 },
{ 5, 2, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 8, 7, 0, 0, 0, 0, 3, 1 },
{ 0, 0, 3, 0, 1, 0, 0, 8, 0 },
{ 9, 0, 0, 8, 6, 3, 0, 0, 5 },
{ 0, 5, 0, 0, 9, 0, 6, 0, 0 },
{ 1, 3, 0, 0, 0, 0, 2, 5, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 7, 4 },
{ 0, 0, 5, 2, 0, 6, 3, 0, 0 } };
if (solveSudoku(grid, 0, 0))
print(grid);
else
Output
316578492
529134768
487629531
263415987
974863125
851792643
138947256
692351874
745286319
Complexity Analysis:
Method 2: Backtracking.
Approach:
Like all other Backtracking problems, Sudoku can be solved by one by one assigning numbers
to empty cells. Before assigning a number, check whether it is safe to assign. Check that the
same number is not present in the current row, current column and current 3X3 subgrid. After
checking for safety, 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 try the next number for
the current empty cell. And if none of the number (1 to 9) leads to a solution, return false and
print no solution exists.
Algorithm:
1. Create a function that checks after assigning the current index the grid becomes unsafe
or not. Keep Hashmap for a row, column and boxes. If any number has a frequency
greater than 1 in the hashMap return false else return true; hashMap can be avoided by
using loops.
2. Create a recursive function that takes a grid.
3. Check for any unassigned location. If present then assign a number from 1 to 9, check if
assigning the number to current index makes the grid unsafe or not, if safe then
recursively call the function for all safe cases from 0 to 9. if any recursive call returns
true, end the loop and return true. If no recursive call returns true then return false.
4. If there is no unassigned location then return true.
Implementation:
C++Java
/* A Backtracking program in
class GFG {
if (board[row][d] == num) {
return false;
}
// Column has the unique numbers (column-clash)
// we are trying to
if (board[r][col] == num) {
return false;
r++) {
if (board[r][d] == num) {
return false;
}
// if there is no clash, it's safe
return true;
if (board[i][j] == 0) {
row = i;
col = j;
isEmpty = false;
break;
if (!isEmpty) {
break;
}
// No empty space left
if (isEmpty) {
return true;
board[row][col] = num;
if (solveSudoku(board, n)) {
// print(board, n);
return true;
else {
// replace it
board[row][col] = 0;
return false;
System.out.print(board[r][d]);
System.out.print(" ");
System.out.print("\n");
if ((r + 1) % (int)Math.sqrt(N) == 0) {
System.out.print("");
// Driver Code
int[][] board
= new int[][] { { 3, 0, 6, 5, 0, 8, 4, 0, 0 },
{ 5, 2, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 8, 7, 0, 0, 0, 0, 3, 1 },
{ 0, 0, 3, 0, 1, 0, 0, 8, 0 },
{ 9, 0, 0, 8, 6, 3, 0, 0, 5 },
{ 0, 5, 0, 0, 9, 0, 6, 0, 0 },
{ 1, 3, 0, 0, 0, 0, 2, 5, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 7, 4 },
{ 0, 0, 5, 2, 0, 6, 3, 0, 0 } };
int N = board.length;
if (solveSudoku(board, N)) {
// print solution
print(board, N);
else {
System.out.println("No solution");
// by MohanDas
Output
316578492
529134768
487629531
263415987
974863125
851792643
138947256
692351874
745286319
Complexity Analysis: