Count Paths

Given a grid, count the number of paths from the top-left to the bottom-right.


Problem from structy.net

Write a function, countPaths, that takes in a grid as an argument. In the grid, 'X' represents walls and 'O' represents open spaces. You may only move down or to the right and cannot pass through walls. The function should return the number of ways possible to travel from the top-left corner of the grid to the bottom-right corner.

My solution:

const stringifyCoords = (x, y) => {
  return `${x}, ${y}`;
}
 
const countPaths = (grid, row = 0, col = 0, cache = {}) => {
  const isEndOfCol = col === grid[0].length - 1;
  const isEndOfRow = row === grid.length - 1;
  const isColOutOfBounds = col > grid[0].length - 1;
  const isRowOutOfBounds = row > grid.length - 1;
  const cacheKey = stringifyCoords(row, col);
  
  if(cache[cacheKey] !== undefined) {
    return cache[cacheKey];
  } else if(isColOutOfBounds || isRowOutOfBounds || grid[row][col] === "X" ) {
    return 0;
  } else if(isEndOfRow && isEndOfCol && grid[row][col] === "O") {
    return 1;
  } else {
    cache[cacheKey] = 
      countPaths(grid, row + 1, col, cache) + countPaths(grid, row, col + 1, cache);
    
    return cache[cacheKey];
  }
}

This one took me a lot of time to get, but at least I was not lost throughout it. I had some trouble with how to iterate through the grid at first, but found a recursive solution pretty quickly. That left me failing on the large grid test case, so I knew to add in a cache/memoization to not repeat work already done. I struggled a bit there and had to put it down for a little while. I think ultimately my problem was I was not passing the cache through on subsequent countPaths calls. I missed that issue for a while, so I wasted a lot of time breaking and fixing my algorithm in different places. I'm not hating it as much as the last one either. That's making me optimistic.