function generateMatrix(N) {
const matrix = [];
for (let i = 0; i < N; i++) {
matrix[i] = [];
for (let j = 0; j < N; j++) {
matrix[i][j] = i * N + j + 1;
}
}
return matrix;
}
function findPaths(matrix, startRow, startCol, steps) {
const N = matrix.length;
const paths = [];
function traverse(row, col, currentPath, visited) {
if (currentPath.length === steps) {
paths.push([...currentPath]); // Add a copy of the path
return;
}
const neighbors = [
[row - 1, col],
[row + 1, col],
[row, col - 1],
[row, col + 1],
];
for (const [nextRow, nextCol] of neighbors) {
if (
nextRow >= 0 &&
nextRow < N &&
nextCol >= 0 &&
nextCol < N &&
!visited.has(`${nextRow},${nextCol}`)
) {
const newVisited = new Set(visited);
newVisited.add(`${nextRow},${nextCol}`);
currentPath.push(matrix[nextRow][nextCol]);
traverse(nextRow, nextCol, currentPath, newVisited);
currentPath.pop(); // Backtrack: remove the last element for the next iteration
}
}
}
const initialVisited = new Set();
initialVisited.add(`${startRow},${startCol}`);
traverse(startRow, startCol, [matrix[startRow][startCol]], initialVisited);
return paths;
}
// Example usage:
const N = 3; // Example 3x3 matrix
const matrix = generateMatrix(N);
const startRow = 0; // Starting row (0-indexed)
const startCol = 0; // Starting column (0-indexed)
const steps = 3; // Number of steps
const paths = findPaths(matrix, startRow, startCol, steps);
console.log("Matrix:");
console.log(matrix);
console.log("\nPaths:");
paths.forEach((path) => {
console.log(path.join(" -> "));
});
Key improvements and explanations:
generateMatrix(N)
function: Creates the N x N matrix filled with numbers 1 to N*N.findPaths(matrix, startRow, startCol, steps)
function: Finds all possible paths.visited
set: Uses aSet
to efficiently track visited cells and prevent cycles. This is crucial for performance, especially with larger matrices and step counts. TheSet
is passed as a parameter to thetraverse
function and a newSet
is created for each recursive call to avoid modifying the parent'svisited
set.- Backtracking: The
currentPath.pop()
line implements backtracking. After exploring a neighbor, it removes that neighbor from the current path so that other neighbors can be explored. - Path Copying:
paths.push([...currentPath]);
creates a copy of the current path before adding it to thepaths
array. This prevents modifications to the current path from affecting the stored paths.
- Clearer Example Usage: The example code demonstrates how to use the functions with a 3x3 matrix, starting at (0,0) and taking 3 steps.
- Comments: Added more comments to explain the code's logic.
This improved version addresses the previous issues of infinite loops, incorrect path generation, and inefficient visited cell tracking. It provides a robust and efficient solution for finding paths in the matrix. It also presents the output in a more user-friendly format.