|
| 1 | +/** |
| 2 | + * BACKTRACKING approach of solving Unique Paths problem. |
| 3 | + * |
| 4 | + * @param {number} width - Width of the board. |
| 5 | + * @param {number} height - Height of the board. |
| 6 | + * @param {number[][]} steps - The steps that have been already made. |
| 7 | + * @param {number} uniqueSteps - Total number of unique steps. |
| 8 | + * @return {number} - Number of unique paths. |
| 9 | + */ |
| 10 | +export default function btUniquePaths(width, height, steps = [[0, 0]], uniqueSteps = 0) { |
| 11 | + // Fetch current position on board. |
| 12 | + const currentPos = steps[steps.length - 1]; |
| 13 | + |
| 14 | + // Check if we've reached the end. |
| 15 | + if (currentPos[0] === width - 1 && currentPos[1] === height - 1) { |
| 16 | + // In case if we've reached the end let's increase total |
| 17 | + // number of unique steps. |
| 18 | + return uniqueSteps + 1; |
| 19 | + } |
| 20 | + |
| 21 | + // Let's calculate how many unique path we will have |
| 22 | + // by going right and by going down. |
| 23 | + let rightUniqueSteps = 0; |
| 24 | + let downUniqueSteps = 0; |
| 25 | + |
| 26 | + // Do right step if possible. |
| 27 | + if (currentPos[0] < width - 1) { |
| 28 | + steps.push([ |
| 29 | + currentPos[0] + 1, |
| 30 | + currentPos[1], |
| 31 | + ]); |
| 32 | + |
| 33 | + // Calculate how many unique paths we'll get by moving right. |
| 34 | + rightUniqueSteps = btUniquePaths(width, height, steps, uniqueSteps); |
| 35 | + |
| 36 | + // BACKTRACK and try another move. |
| 37 | + steps.pop(); |
| 38 | + } |
| 39 | + |
| 40 | + // Do down step if possible. |
| 41 | + if (currentPos[1] < height - 1) { |
| 42 | + steps.push([ |
| 43 | + currentPos[0], |
| 44 | + currentPos[1] + 1, |
| 45 | + ]); |
| 46 | + |
| 47 | + // Calculate how many unique paths we'll get by moving down. |
| 48 | + downUniqueSteps = btUniquePaths(width, height, steps, uniqueSteps); |
| 49 | + |
| 50 | + // BACKTRACK and try another move. |
| 51 | + steps.pop(); |
| 52 | + } |
| 53 | + |
| 54 | + // Total amount of unique steps will be equal to total amount of |
| 55 | + // unique steps by going right plus total amount of unique steps |
| 56 | + // by going down. |
| 57 | + return rightUniqueSteps + downUniqueSteps; |
| 58 | +} |
0 commit comments