Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
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:
-
Setup: Calculate total empty squares and define movement directions
-
DFS Function: Explores all possible paths from current position
-
Base Case: When reaching the end square (value 2), check if all empty squares were visited
-
Backtracking: Mark cells as visited (-1) during exploration, then restore original values when backtracking
-
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.
