構造一個自定義二維 N*N 矩陣,從左上角第一個單元格依次填入1 - N*N的數字,從矩陣中指定單元格出發,經過相鄰的單元格(不可重複),走 X 步,輸出所有可能的路徑和每條路徑單元格對應的數字。

王铁柱6發表於2024-12-05
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 a Set to efficiently track visited cells and prevent cycles. This is crucial for performance, especially with larger matrices and step counts. The Set is passed as a parameter to the traverse function and a new Set is created for each recursive call to avoid modifying the parent's visited 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 the paths 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.

相關文章