The algorithm problem - Backtracing pattern in JavaScript

Backtracking is a powerful algorithmic pattern for solving constraint satisfaction problems. In this grid path problem, we need to find all possible paths from start to end that visit every walkable square exactly once.

Problem Definition

Given a 2D grid with different square types, find the number of unique paths from start to end:

  • 1 represents the starting square (exactly one)

  • 2 represents the ending square (exactly one)

  • 0 represents empty squares we can walk over

  • -1 represents obstacles we cannot walk over

The path must visit every non-obstacle square exactly once using 4-directional movement (up, down, left, right).

Algorithm Overview

Sample Grid: 1 0 0 0 0 2 Backtracking Steps: 1. Start from position (0,0) 2. Mark current cell as visited (-1) 3. Try all 4 directions 4. If target reached and all cells visited ? count++ 5. Backtrack: restore cell to original value

Implementation

const arr = [
    [1,0,0,0],
    [0,0,0,0],
    [0,0,2,-1]
];

const uniquePaths = (arr, count = 0) => {
    const dy = [1,-1,0,0], dx = [0,0,1,-1];
    const m = arr.length, n = arr[0].length;
    
    // Count total empty squares (0s) that must be visited
    const totalZeroes = arr.map(row => row.filter(num => num === 0).length)
                           .reduce((total, rowZeroes) => total + rowZeroes, 0);
    
    const depthFirstSearch = (i, j, covered) => {
        // Base case: reached the ending square
        if (arr[i][j] === 2){
            if (covered === totalZeroes + 1) count++;
            return;
        }
        
        // Try all 4 directions
        for (let k = 0; k = 0 && newI = 0 && newJ 

2

How It Works

The algorithm uses depth-first search with backtracking:

  1. Setup: Calculate total empty squares and define movement directions
  2. DFS Function: Explores all possible paths from current position
  3. Base Case: When reaching the end square (value 2), check if all empty squares were visited
  4. Backtracking: Mark cells as visited (-1) during exploration, then restore original values when backtracking
  5. Direction Exploration: Try all 4 directions (up, down, left, right) from each position

Key Points

  • Time complexity is exponential O(4^(m×n)) in worst case due to exploring all possible paths

  • Space complexity is O(m×n) for the recursion stack

  • The algorithm ensures each walkable square is visited exactly once

  • Backtracking is essential to explore all valid path combinations

Conclusion

This backtracking solution systematically explores all possible paths while maintaining the constraint of visiting each square exactly once. The pattern is widely applicable to constraint satisfaction problems requiring exhaustive search with state restoration.

Updated on: 2026-03-15T23:19:00+05:30

267 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements