Backtracking is a technique used to solve problems recursively by trying out all possible solutions.
If a solution is found, it proceeds, otherwise, it backs up and tries a different approach.
This method is often used in constraint satisfaction problems, such as puzzles like Sudoku, as well as in other optimization and search problems.
pseudocode:
procedure Backtrack(state):
if state is a solution:
return state
else:
for each possible choice for the next step:
if the choice is valid:
make the choice
result = Backtrack(new_state)
if result is not None:
return result
undo the choice
return None
initial_state = initial_state_of_the_problem
solution = Backtrack(initial_state)
if solution is not None:
// Process solution
else:
// No solution found
Example of backtracking algorithm to solve the N-Queens problem using JavaScript:
functionisSafe(board, row, col, N) {// Check if there is a queen in the same row to the leftfor (let i =0; i < col; i++) {if (board[row][i]) {returnfalse; } }// Check upper diagonal on left sidefor (let i = row, j = col; i >=0&& j >=0; i--, j--) {if (board[i][j]) {returnfalse; } }// Check lower diagonal on left sidefor (let i = row, j = col; j >=0&& i <N; i++, j--) {if (board[i][j]) {returnfalse; } }returntrue;}functionsolveNQueensUtil(board, col, N, result) {// Base case: If all queens are placed, return trueif (col >=N) {result.push([...board.map(row =>row.join(''))]);return; }// Consider this column and try placing this queen in all rows one by onefor (let i =0; i <N; i++) {if (isSafe(board, i, col,N)) { board[i][col] =1;// Recur to place rest of the queenssolveNQueensUtil(board, col +1,N, result);// If placing queen in board[i][col] doesn't lead to a solution then remove queen from board[i][col] board[i][col] =0; // Backtrack } }}functionsolveNQueens(N) {constboard=Array.from({ length:N }, () =>Array(N).fill(0));constresult= [];solveNQueensUtil(board,0,N, result);return result;}// Example usage:constN=4;constsolutions=solveNQueens(N);console.log("Solutions for N =",N);solutions.forEach(solution =>console.log(solution));
This code solves the N-Queens problem recursively using backtracking.
It finds all possible placements of N queens on an NxN chessboard such that no two queens attack each other.