Easy-to-Read JavaScript Solution w/ Explanation!
Easy-to-Read JavaScript Solution w/ Explanation!\nThis was kind of a medium-hard problem.\n\n# Intuition\nLooking at this problem, it is obvious some form of DF
# Easy-to-Read JavaScript Solution w/ Explanation!\nThis was kind of a medium-hard problem.\n\n# Intuition\nLooking at this problem, it is obvious some form of DFS is necessary to traverse the graph, and find all possible routes. However, we then look at the constraints and realize that we also need Dynamic Programming, or more specifically, memoization, to reduce time usage. Based on these things, we can write the following solution.\n\n# Approach\nFirst, let\'s think about how we store things in the DFS memo. It seems necessary to use a 2-dimensional memo, because we need to keep in mind two parameters: The current position, and how much fuel we have left.\n\nIn execution, we use a JS `Map`, which stores a key of `${position},${fuel}`, and a value of how many paths to finish there are from that specific state.\n\nNow, all we have to do is run a DFS through the array, keeping track of the current position and fuel left. If we have cached a result, use that. If no cache was found, at each position, run DFS on every other position that we can reach with our remaining fuel, and save that to cache.\n\nWe call DFS on the start node, with the original amount of fuel.\n\n# Code\n```\nvar countRoutes = function (locations, start, finish, fuel) {\n    // Map to keep track of visited nodes and paths to end with those conditions\n    let visited = new Map();\n\n    // Modulo to use\n    let mod = 10 ** 9 + 7;\n\n    // DFS function\n    let dfs = (current, fuel) => {\n        // Generate a key in the "2D" memo matrix\n        let id = `${current},${fuel}`\n\n        // If we haven\'t visited already...\n        if (!visited.has(id)) {\n            let paths = 0;\n            // Count the paths; if we already finished, increment paths\n            if (current === finish) paths++;\n            // Go through all other positions...\n            for (let i = 0; i < locations.length; i++) {\n                if (i !== current) {\n                    // Calculate remaining fuel\n                    let remaining = fuel - Math.abs(locations[current] - locations[i]);\n                    // If sufficient fuel, DFS further from current position\n                    if (remaining >= 0) {\n                        paths += dfs(i, remaining);\n                    }\n                }\n            }\n            visited.set(id, paths % mod)\n        }\n\n        // Finally, cache result\n        return visited.get(id);\n    }\n\n    // Run DFS on starting node\n    return dfs(start, fuel);\n};\n```\n\n### Please upvote if this helped!\n<br/>
['JavaScript']