1+ ##==================================
2+ ## Leetcode
3+ ## Student: Vandit Jyotindra Gajjar
4+ ## Year: 2020
5+ ## Problem: 79
6+ ## Problem Name: Word Search
7+ ##===================================
8+ #
9+ #Given a 2D board and a word, find if the word exists in the grid.
10+ #
11+ #The word can be constructed from letters of sequentially adjacent cell,
12+ #where "adjacent" cells are those horizontally or vertically neighboring.
13+ #The same letter cell may not be used more than once.
14+ #
15+ #Example:
16+ #
17+ #board =
18+ #[
19+ # ['A','B','C','E'],
20+ # ['S','F','C','S'],
21+ # ['A','D','E','E']
22+ #]
23+ #
24+ #Given word = "ABCCED", return true.
25+ #Given word = "SEE", return true.
26+ #Given word = "ABCB", return false.
27+ class Solution :
28+ def exist (self , board , word ):
29+ for i , r in enumerate (board ): #Loop through board
30+ for j , value in enumerate (r ): #Loop through r, row basically
31+ if value == word [0 ]: #Condition-check: If we find the letter
32+ if self .dfs (i , j , 0 , board , word ) #Condition-check: If by applying dfs we find the neighboring word
33+ return True #We return True if find the word
34+ return False #Else We return false
35+ def dfs (self , i , j , index , board , word ): #Defining helper method dfs
36+ if index == len (word ): #Condition-check: If index is equal to len(word)
37+ return True #We return True
38+ if not (0 <= i < len (board ) and 0 <= j < len (board [i ])) or board [i ][j ] != word [index ]: #Condition-check
39+ return False #We return false
40+ tmp = board [i ][j ] #Initialize tmp board
41+ board [i ][j ] = '+' #Update the value by '+'
42+ for nI , nJ in (i + 1 , j ), (i - 1 , j ), (i , j + 1 ), (i , j - 1 ): #For neighboring elements
43+ if self .dfs (nI , nJ , index + 1 , board , word ): #Condition-check: If by applying dfs we find the word
44+ return True #We return True
45+ board [i ][j ] = tmp #Update board values by tmp
46+ return True #We return True
0 commit comments