Similar Problems
Similar Problems not available
Number Of Good Paths - Leetcode Solution
Companies:
LeetCode: Number Of Good Paths Leetcode Solution
Difficulty: Hard
Topics: hash-table union-find tree array graph sorting
Problem Statement:
Given a positive integer n, you need to count all possible distinct good paths in a n x n grid. A good path is a path from the upper-left cell (1, 1) to the lower-right cell (n, n) that satisfies the following conditions:
The path only contains cells in the diagonal direction (i.e. cells (i, j) such that i==j). For every pair of consecutive cells (i, j) and (i+1, j+1) in the path, either the color of cell (i, j) and cell (i+1, j+1) must be the same, or cell(i, j) and cell(i+1, j+1) must be both white (i.e. have a value of 0). Two paths are considered distinct if and only if there is at least one cell that belongs to one path and does not belong to the other. For example, the paths (1, 1) -> (2, 2) -> (3, 3) and (1, 1) -> (3, 3) are considered distinct. Return the number of distinct good paths modulo 109+7.
Example:
Input: n = 2 Output: 1 Explanation: A good path can only be diagonal cells (1, 1) -> (2, 2) and (2, 2) -> (1, 1).
Solution:
First of all, we need to understand what a good path is. Given the description, a good path is a path that starts from (1,1) and ends at (n,n) and only contains diagonal moves and satisfies the following two conditions:
For every pair of consecutive cells (i,j) and (i+1,j+1) in the path, either the color of cell (i,j) and cell (i+1,j+1) must be the same, or cell(i,j) and cell(i+1,j+1) must be both white (i.e. have a value of 0). The path only contains cells in the diagonal direction (i.e. cells (i,j) such that i==j).
To count the number of good paths, we can use dynamic programming. Let's define dp[i][j][k] as the number of good paths that start from cell (i,j) and ends at cell (n,n) and the color of cell (i,j) is k. Here, 0 represents a white cell, and 1 represents a black cell. We can initialize dp[n][n][0] and dp[n][n][1] as 1 because there is only one possible path that starts and ends at cell (n,n).
To compute dp[i][j][k], we need to consider two cases:
If cell (i,j) has the same color as cell (i+1,j+1), then we can only move diagonally to cell (i+1,j+1) and stay in the same color. dp[i][j][k] = dp[i+1][j+1][k]
If cell (i,j) and cell (i+1,j+1) are both white, then we can either move diagonally to cell (i+1,j+1) and stay in the same color or move diagonally to cell (i+1,j+1) and switch colors. dp[i][j][k] = dp[i+1][j+1][k] + dp[i+1][j+1][1-k]
The answer will be dp[1][1][0] + dp[1][1][1] (since we can start with either white or black cell).
The time complexity of the above solution is O(n^3), and the space complexity is O(n^3) as well. However, we can optimize the space complexity to O(n^2) by keeping only the previous and current rows of the dp array.
Number Of Good Paths Solution Code
1