- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Escape a Large Maze Python
Suppose we have a grid, there are 1 million rows and 1 million columns, we also have one list of blocked cells. Now we will start at the source square and want to reach the target square. In each move, we can walk to a up, down, left, right adjacent square in the grid that isn't in the given list of blocked cells.
We have to check whether it is possible to reach the target square through a sequence of moves or not.
So, if the input is like blocked = [[0,1],[1,0]], source = [0,0], target = [0,3], then the output will be False
To solve this, we will follow these steps −
blocked := make a set of all blocked cells
Define one method dfs(), this will take x, y, target and seen
if (x,y) are not in range of grids or (x,y) is in blocked or (x,y) is in seen then
add (x,y) into seen
if size of seen > 20000 or (x,y) is target, then
return dfs(x+1,y,target,seen) or dfs(x-1,y,target,seen) or dfs(x,y+1,target,seen) or dfs(x,y-1,target,seen)
return dfs(source, source, target, empty set) and dfs(target, target, source, empty set)
Let us see the following implementation to get better understanding −
class Solution(object): def isEscapePossible(self, blocked, source, target): blocked = set(map(tuple, blocked)) def dfs(x, y, target, seen): if not (0 <= x < 10**6 and 0 <= y < 10**6) or (x, y) in blocked or (x, y) in seen: return False seen.add((x, y)) if len(seen) > 20000 or [x, y] == target: return True return dfs(x + 1, y, target, seen) or \ dfs(x - 1, y, target, seen) or \ dfs(x, y + 1, target, seen) or \ dfs(x, y - 1, target, seen) return dfs(source, source, target, set()) and dfs(target, target, source, set()) ob = Solution() print(ob.isEscapePossible([[0,1],[1,0]], [0,0], [0,3]))
[[0,1],[1,0]], [0,0], [0,3]
- Minimum number of moves to escape maze matrix in Python
- Escape Characters in Python
- Rat in a Maze Problem
- The Maze in C++
- Ways to print escape characters in python
- How to process escape sequences in a string in Python?
- The Maze III in C++
- The Maze II in C++
- How do I un-escape a backslash-escaped string in Python?
- Python program to find factorial of a large number
- C Program for Rat in a Maze - Backtracking-2?
- Positions of Large Groups in Python
- Escape sequences in Java
- Escape sequences in C