The algorithm problem - Backtracing pattern in JavaScript

JavascriptFront End TechnologyObject Oriented ProgrammingWeb Development

Consider the following backtracing problem: On a 2−dimensional grid, there are 4 types of squares −

  • 1 represents the starting square. There is exactly one starting square.

  • 2 represents the ending square. There is exactly one ending square.

  • 0 represents empty squares we can walk over.

  • −1 represents obstacles that we cannot walk over.

We are required to write a function that returns the number of 4−directional walks from the starting square to the ending square, that walk over every non−obstacle square exactly once.

Example

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;
   const totalZeroes = arr.map(row => row.filter(num => num ===
   0).length).reduce((totalZeroes,nextRowZeroes) => totalZeroes +
   nextRowZeroes, 0);
   const depthFirstSearch = (i, j, covered) => {
      if (arr[i][j] === 2){
         if (covered === totalZeroes + 1) count++;
         return;
      };
      for (let k = 0; k < 4; k++)
      if (i+dy[k] >= 0 && i+dy[k] < m && j+dx[k] >= 0 && j+dx[k] < n
      && arr[i+dy[k]][j+dx[k]] !== −1 ){
         arr[i][j] = −1;
         depthFirstSearch(i+dy[k],j+dx[k],covered+1);
         arr[i][j] = 0;
      }
      return;
   };
   for (let row = 0; row < m; row++)
   for (let col = 0; col < n; col++)
   if (arr[row][col] === 1){
      arr[row][col] = −1;
      depthFirstSearch(row,col,0);
      break;
   }
   return count;
};
console.log(uniquePaths(arr));

Explanation

  • We set up variables to facilitate four directional iteration when traversing grid, count zeroes in matrix to allow for checking coverage when base condition of recursion reached

  • Then we set up the DFS (Depth First Search) backtrack function to mark grid with −1 on the active path and to check path length when the finish cell is reached

  • And lastly, we launch the DFS from the start cell to count all full paths and return the count

Output

And the output in the console will be −

2
raja
Published on 21-Nov-2020 09:26:17
Advertisements