Create Grid With Exactly One Path Problem
#3963
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3963.
You are given two integers m and n, representing the number of rows and columns of a grid.
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 is exactly one valid path from the top-left cell to the bottom-right cell.
Example 1:
Input: m = 2, n = 3
Output: ["..#","#.."]
Explanation:

The only valid path is: (0,0) → (0,1) → (1,1) → (1,2)
Example 2:
Input: m = 3, n = 3
Output: ["..#","#..","##."]
Explanation:

The only valid path is: (0,0) → (0,1) → (1,1) → (1,2) → (2,2)
Example 3:
Input: m = 1, n = 4
Output: ["...."]
Explanation:
The only valid path is: (0,0) → (0,1) → (0,2) → (0,3)
Constraints:
1 <= m, n <= 25
Solution
Approach: Construction
Start with a grid full of #, then make the whole first row and the whole last column free (.). The only way to go right and down from the top-left to the bottom-right through free cells is along the first row and then down the last column, so there is exactly one path.
Complexity: time O(m * n), space O(m * n).
class Solution:
def createGrid(self, m: int, n: int) -> List[str]:
g = [["#"] * n for _ in range(m)]
g[0] = ["."] * n
for i in range(m):
g[i][-1] = "."
return ["".join(row) for row in g]