HardNo. 1036

Escape a Large Maze — LeetCode 1036 Python Solution

Topics
Depth-First Search, Breadth-First Search, Array, Hash Table
Reading time
4 min

The problem

There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are (x, y). We start at the source = [sx, sy] square and want to reach the target = [tx, ty] square.

Example

Input
blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]
Output
false
Explanation
The target square is inaccessible starting from the source square because we cannot move.

Python solution

PythonSolution
class Solution:
    def isEscapePossible(
        self, blocked: List[List[int]], source: List[int], target: List[int]
    ) -> bool:
        def dfs(source: List[int], target: List[int], vis: set) -> bool:
            vis.add(tuple(source))
            if len(vis) > m:
                return True
            for a, b in pairwise(dirs):
                x, y = source[0] + a, source[1] + b
                if 0 <= x < n and 0 <= y < n and (x, y) not in s and (x, y) not in vis:
                    if [x, y] == target or dfs([x, y], target, vis):
                        return True
            return False

        s = {(x, y) for x, y in blocked}
        dirs = (-1, 0, 1, 0, -1)
        n = 10**6
        m = len(blocked) ** 2 // 2
        return dfs(source, target, set()) and dfs(target, source, set())

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Breadth-First Search

Expand outward level by level, so the first time you arrive is the shortest way. LeetCode 1036. Escape a Large Maze is filed here because LeetCode tags it Breadth-First Search, which is the vocabulary this hub collects.

The breadth-first search guide has the Python template for the pattern and the 233 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0690Employee ImportanceMedium
0721Accounts MergeMedium
0839Similar String GroupsHard
0924Minimize Malware SpreadHard
0928Minimize Malware Spread IIHard
0959Regions Cut By SlashesMedium

Frequently asked questions

How hard is LeetCode 1036. Escape a Large Maze?

LeetCode 1036. Escape a Large Maze is rated Hard on LeetCode.

What is the time complexity of LeetCode 1036. Escape a Large Maze?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 1036. Escape a Large Maze?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 1036. Escape a Large Maze cover?

LeetCode 1036. Escape a Large Maze is tagged Depth-First Search, Breadth-First Search, Array and Hash Table on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.