![]() |
VOOZH | about |
There are 88418 paths in a 7x7 grid from the upper-left square to the lower-left square. Each path corresponds to a 48-character description consisting of characters D (down), U (up), L (left) and R (right). You are given a description of a path which may also contain characters ? (any direction). Your task is to calculate the number of paths that match the description.
Example
Input: ??????R??????U??????????????????????????LD????D?
Output: 201
Explanation: There are 201 possible paths with the given description.
The idea is to use DFS and try all four directions if the current character in the string is ‘?’ else we go in direction given (L,R,U,D).
Pruning/Terminating the search in order to optimize the code:
If we cannot go up or down but can turn either left or right or if we cannot turn left or right but can go up and down, in this case the grid splits into two parts. It is clear that we cannot visit one part of the grid, so we can terminate the search. These four cases also leaves unvisited squares which can cannot be visited. Hence, the search needs to terminate.
- If the upper-right diagonal square is visited and the up and right squares are unvisited.
- If the lower-right diagonal square is visited and the down and right squares are unvisited.
- If the upper-left diagonal square is visited and the up and left squares are unvisited.
- If the lower-left diagonal square is visited and the down and right squares are unvisited.
Step-by-step algorithm:
Below is the implementation of the approach:
201
Time Complexity: O(4N), where N is the length of string.
Auxiliary Space: O(N)