Skip to content

Commit 5f68807

Browse files
committed
exist - AC simply code
1 parent 4f812e1 commit 5f68807

File tree

1 file changed

+48
-20
lines changed

1 file changed

+48
-20
lines changed

Diff for: leecode/单词搜索/exist.py

+48-20
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#!/usr/bin/python3
22
# -*- coding: utf-8 -*-
33
'''
4-
AC but ugly
4+
AC
55
'''
66
import sys
77
import time
@@ -20,32 +20,21 @@ def exist(self, board, word):
2020
if len_y ==0:
2121
return False
2222
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)
3223

24+
3325
out_t =False
3426
def backtrack(word_t,x,y):
3527
nonlocal out_t
36-
nonlocal flag
3728
if out_t:
38-
return 0
29+
return out_t
3930

4031
if x <0 or y<0:
4132
return 0
4233
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]="!"
4938
else:
5039
return 0
5140
except IndexError:
@@ -59,7 +48,7 @@ def backtrack(word_t,x,y):
5948
backtrack(word_t,x-1,y)
6049
backtrack(word_t,x,y+1)
6150
backtrack(word_t,x,y-1)
62-
flag[y][x]=0
51+
board[y][x]=temp
6352
return out_t
6453

6554
for i in range(len_y):
@@ -102,6 +91,45 @@ def backtrack(word_t,x,y):
10291
print("\nRun Time is %f s" % (time.perf_counter() - t0))
10392
else:
10493
print("\nRun Time is %f s" % (time.time() - t0))
105-
'''
10694

10795
'''
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

Comments
 (0)