Skip to content

Commit

Permalink
Merge pull request neetcode-gh#2037 from saip7795/sp/word-search
Browse files Browse the repository at this point in the history
Create: 0079-Word-Search.rb
  • Loading branch information
tahsintunan authored Jan 16, 2023
2 parents f4f236e + 44a6d92 commit f8122a4
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions ruby/0079-word-search.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
def exist(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
return false if !(set1 >= set2)

def dfs(r,c,i)
return true if i == @word.length()
return false if (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])

return result
end

(0..@rows-1).each do |r|
(0..@cols-1).each do |c|
return true if dfs(r,c,0)
end
end

return false

end

0 comments on commit f8122a4

Please sign in to comment.