forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0079-word-search.rb
37 lines (28 loc) · 821 Bytes
/
0079-word-search.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
defexist(board,word)
@rows=board.length
@cols=board[0].length
@board=board
@word=word
@path=Set.new()
set1=@board.flatten.to_set
set2=@word.split('').to_set
returnfalseif !(set1 >= set2)
defdfs(r,c,i)
returntrueifi == @word.length()
returnfalseif(r<0 || c<0 || r >= @rows || c >= @cols || @word[i] != @board[r][c] || @path.include?([r,c]))
@path.add([r,c])
result=(dfs(r+1,c,i+1) ||
dfs(r-1,c,i+1) ||
dfs(r,c+1,i+1) ||
dfs(r,c-1,i+1)
)
@path.delete([r,c])
returnresult
end
(0..@rows-1).eachdo |r|
(0..@cols-1).eachdo |c|
returntrueifdfs(r,c,0)
end
end
returnfalse
end