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
return false
add (x,y) into seen
if size of seen > 20000 or (x,y) is target, then
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[0], source[1], target, empty set) and dfs(target[0], target[1], source, empty set)
Let us see the following implementation to get better understanding −
Example
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[0], source[1], target, set()) and dfs(target[0], target[1], source, set()) ob = Solution() print(ob.isEscapePossible([[0,1],[1,0]], [0,0], [0,3]))
Input
[[0,1],[1,0]], [0,0], [0,3]
Output
False