2
def hasValidPath(self, grid: List[List[str]]) -> bool:6
@lru_cache(maxsize=None)7
def hasValidPathInner(x, y, cnt):8
# cnt variable would act as a counter to track9
# the balance of parantheses sequence10
if x == m or y == n or cnt < 0:13
# logic to check the balance of sequence14
cnt += 1 if grid[x][y] == "(" else -116
# if balanced and end of grid, return True17
if x == m - 1 and y == n - 1 and not cnt:20
return hasValidPathInner(x + 1, y, cnt) or hasValidPathInner(x, y + 1, cnt)22
return hasValidPathInner(0, 0, 0)