'How to understand leetcode's word serach best solution in Python?
I'm currently working on solving leetcode's word search task, and i see the fastest solution in Python is like this:
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
def backtracking(r,c,step=0):
if step == len(word):return True
if 0 <= r < m and 0 <= c < n and board[r][c] == word[~step] and (r,c) not in visited:
visited.add((r,c))
Hashmap[(r,c,step)] += 1
for nr,nc in (r,c+1),(r,c-1),(r+1,c),(r-1,c):
if Hashmap[(nr,nc,step+1)] < n:
if backtracking(nr,nc,step+1):
return True
visited.remove((r,c))
return False
m,n = len(board),len(board[0])
visited,Hashmap = set(),collections.defaultdict(int)
for i,j in itertools.product(range(m),range(n)):
if backtracking(i,j):
return True
return False
What confuses me most is how to understand the existence of [Hashmap] and the sentence
if Hashmap[(nr,nc,step+1)] < n:
how does it accelerate the progress?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
