File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ from collections import defaultdict
2+ class Solution :
3+ def exist (self , board : List [List [str ]], word : str ) -> bool :
4+ pos = defaultdict (list )
5+ for i in range (len (board )):
6+ for j in range (len (board [0 ])):
7+ if board [i ][j ] in word :
8+ tmp = pos .get (board [i ][j ], [])
9+ tmp .append ([i , j ])
10+ pos [board [i ][j ]] = tmp
11+
12+ paths = pos .get (word [0 ], [])
13+ paths = [[path ] for path in paths ]
14+
15+ for w in word [1 :]:
16+ temp = []
17+
18+ while len (paths ) > 0 :
19+ path = paths .pop ()
20+ i , j = path [- 1 ]
21+ if ([i , j + 1 ] in pos [w ]) and ([i , j + 1 ] not in path ):
22+ temp .append (path [:] + [[i , j + 1 ]])
23+ if ([i , j - 1 ] in pos [w ]) and ([i , j - 1 ] not in path ):
24+ temp .append (path [:] + [[i , j - 1 ]])
25+ if ([i + 1 , j ] in pos [w ]) and ([i + 1 , j ] not in path ):
26+ temp .append (path [:] + [[i + 1 , j ]])
27+ if ([i - 1 , j ] in pos [w ]) and ([i - 1 , j ] not in path ):
28+ temp .append (path [:] + [[i - 1 , j ]])
29+ paths .extend (temp )
30+ for path in paths :
31+ if len (path ) == len (word ):
32+ return True
33+ return False
You can’t perform that action at this time.
0 commit comments