The algorithm problem - Backtracing pattern in JavaScript

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 = 0 && i+dy[k] = 0 && j+dx[k] 

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
Updated on: 2020-11-21T09:27:55+05:30

260 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements