1
1
#!/usr/bin/python3
2
2
# -*- coding: utf-8 -*-
3
3
'''
4
- AC but ugly
4
+ AC
5
5
'''
6
6
import sys
7
7
import time
@@ -20,32 +20,21 @@ def exist(self, board, word):
20
20
if len_y == 0 :
21
21
return False
22
22
len_x = len (board [0 ])
23
- if len_x == 0 :
24
- return False
25
-
26
- flag = []
27
- for i in range (len_y ):
28
- temp = []
29
- for j in range (len_x ):
30
- temp .append (0 )
31
- flag .append (temp )
32
23
24
+
33
25
out_t = False
34
26
def backtrack (word_t ,x ,y ):
35
27
nonlocal out_t
36
- nonlocal flag
37
28
if out_t :
38
- return 0
29
+ return out_t
39
30
40
31
if x < 0 or y < 0 :
41
32
return 0
42
33
try :
43
- if flag [y ][x ]== 0 :
44
- if board [y ][x ] == word [len (word_t )]:
45
- word_t = word_t + board [y ][x ]
46
- flag [y ][x ]= 1
47
- else :
48
- return 0
34
+ temp = board [y ][x ]
35
+ if temp == word [len (word_t )]:
36
+ word_t = word_t + temp
37
+ board [y ][x ]= "!"
49
38
else :
50
39
return 0
51
40
except IndexError :
@@ -59,7 +48,7 @@ def backtrack(word_t,x,y):
59
48
backtrack (word_t ,x - 1 ,y )
60
49
backtrack (word_t ,x ,y + 1 )
61
50
backtrack (word_t ,x ,y - 1 )
62
- flag [y ][x ]= 0
51
+ board [y ][x ]= temp
63
52
return out_t
64
53
65
54
for i in range (len_y ):
@@ -102,6 +91,45 @@ def backtrack(word_t,x,y):
102
91
print ("\n Run Time is %f s" % (time .perf_counter () - t0 ))
103
92
else :
104
93
print ("\n Run Time is %f s" % (time .time () - t0 ))
105
- '''
106
94
107
95
'''
96
+ class Solution:
97
+ # @param board, a list of lists of 1 length string
98
+ # @param word, a string
99
+ # @return a boolean
100
+ def exist(self, board, word):
101
+ def dfs(x, y, word):
102
+ if len(word)==0: return True
103
+ #up
104
+ if x>0 and board[x-1][y]==word[0]:
105
+ tmp=board[x][y]; board[x][y]='#'
106
+ if dfs(x-1,y,word[1:]):
107
+ return True
108
+ board[x][y]=tmp
109
+ #down
110
+ if x<len(board)-1 and board[x+1][y]==word[0]:
111
+ tmp=board[x][y]; board[x][y]='#'
112
+ if dfs(x+1,y,word[1:]):
113
+ return True
114
+ board[x][y]=tmp
115
+ #left
116
+ if y>0 and board[x][y-1]==word[0]:
117
+ tmp=board[x][y]; board[x][y]='#'
118
+ if dfs(x,y-1,word[1:]):
119
+ return True
120
+ board[x][y]=tmp
121
+ #right
122
+ if y<len(board[0])-1 and board[x][y+1]==word[0]:
123
+ tmp=board[x][y]; board[x][y]='#'
124
+ if dfs(x,y+1,word[1:]):
125
+ return True
126
+ board[x][y]=tmp
127
+ return False
128
+
129
+ for i in range(len(board)):
130
+ for j in range(len(board[0])):
131
+ if board[i][j]==word[0]:
132
+ if(dfs(i,j,word[1:])):
133
+ return True
134
+ return False
135
+ '''
0 commit comments