Create Grid With Exactly K Paths I Problem
Description
LeetCode Problem 3988.
You are given three integers m, n, and k.
Construct any m x n grid consisting only of the characters '.' and '#', where:
'.'represents a free cell.'#'represents an obstacle cell.
A valid path is a sequence of free cells that:
- Starts at the top-left cell
(0, 0). - Ends at the bottom-right cell
(m - 1, n - 1). - Moves only:
- Right, from
(i, j)to(i, j + 1), or - Down, from
(i, j)to(i + 1, j).
- Right, from
Return any grid such that there are exactly k valid paths from the top-left cell to the bottom-right cell. If no such grid exists, return an empty array.
Example 1:
Input: m = 2, n = 3, k = 2
Output: ["...","#.."]
Explanation:

There are exactly k = 2 valid paths from (0, 0) to (1, 2):
- (0, 0) → (0, 1) → (0, 2) → (1, 2)
- (0, 0) → (0, 1) → (1, 1) → (1, 2)
Example 2:
Input: m = 3, n = 3, k = 4
Output: ["..#","...","#.."]
Explanation:

There are exactly k = 4 valid paths from (0, 0) to (2, 2):
- (0, 0) → (0, 1) → (1, 1) → (1, 2) → (2, 2)
- (0, 0) → (0, 1) → (1, 1) → (2, 1) → (2, 2)
- (0, 0) → (1, 0) → (1, 1) → (1, 2) → (2, 2)
- (0, 0) → (1, 0) → (1, 1) → (2, 1) → (2, 2)
Example 3:
Input: m = 1, n = 4, k = 2
Output: []
Explanation:
No grid exists with exactly k = 2 valid paths for a 1 x 4 grid, so the answer is an empty array.
Constraints:
1 <= m, n <= 101 <= k <= 4
Solution
Approach: Construction
A completely free a x b block has C(a + b - 2, a - 1) monotone paths from its top-left to its bottom-right cell. With k <= 4 only a few small blocks are needed: 1 x 1 gives 1 path, 2 x 2 gives 2, 2 x 3 or 3 x 2 gives 3, and 2 x 4 or 4 x 2 gives 4.
Put the chosen block in the bottom-right corner of the grid and connect it to the start with a single corridor: go down the first column and then right along the top row of the block, leaving every other cell as an obstacle. The corridor has exactly one route, so the grid has exactly as many paths as the block.
If no block of the right size fits, no grid exists, except for the case 3 x 3 with k = 4, where the grid "..#", "...", "#.." has 4 paths. Otherwise (for example when m = 1 and k > 1) return an empty array.
Complexity: time O(m * n), space O(m * n).
class Solution:
def createGrid(self, m: int, n: int, k: int) -> List[str]:
# A free a x b block in the bottom-right corner has C(a + b - 2, a - 1) paths,
# and a single corridor from the top-left corner leads to it.
shapes = {1: [(1, 1)], 2: [(2, 2)], 3: [(2, 3), (3, 2)], 4: [(2, 4), (4, 2)]}[k]
for a, b in shapes:
if a <= m and b <= n:
g = [['#'] * n for _ in range(m)]
for i in range(m - a + 1):
g[i][0] = '.'
for j in range(n - b + 1):
g[m - a][j] = '.'
for i in range(m - a, m):
for j in range(n - b, n):
g[i][j] = '.'
return [''.join(row) for row in g]
if (m, n, k) == (3, 3, 4):
return ["..#", "...", "#.."]
return []