当前位置:   article > 正文

Golang | Leetcode Golang题解之第212题单词搜索II

Golang | Leetcode Golang题解之第212题单词搜索II

题目:

题解:

  1. type Trie struct {
  2. children map[byte]*Trie
  3. word string
  4. }
  5. func (t *Trie) Insert(word string) {
  6. node := t
  7. for i := range word {
  8. ch := word[i]
  9. if node.children[ch] == nil {
  10. node.children[ch] = &Trie{children: map[byte]*Trie{}}
  11. }
  12. node = node.children[ch]
  13. }
  14. node.word = word
  15. }
  16. var dirs = []struct{ x, y int }{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}
  17. func findWords(board [][]byte, words []string) (ans []string) {
  18. t := &Trie{children: map[byte]*Trie{}}
  19. for _, word := range words {
  20. t.Insert(word)
  21. }
  22. m, n := len(board), len(board[0])
  23. var dfs func(node *Trie, x, y int)
  24. dfs = func(node *Trie, x, y int) {
  25. ch := board[x][y]
  26. nxt := node.children[ch]
  27. if nxt == nil {
  28. return
  29. }
  30. if nxt.word != "" {
  31. ans = append(ans, nxt.word)
  32. nxt.word = ""
  33. }
  34. if len(nxt.children) > 0 {
  35. board[x][y] = '#'
  36. for _, d := range dirs {
  37. nx, ny := x+d.x, y+d.y
  38. if 0 <= nx && nx < m && 0 <= ny && ny < n && board[nx][ny] != '#' {
  39. dfs(nxt, nx, ny)
  40. }
  41. }
  42. board[x][y] = ch
  43. }
  44. if len(nxt.children) == 0 {
  45. delete(node.children, ch)
  46. }
  47. }
  48. for i, row := range board {
  49. for j := range row {
  50. dfs(t, i, j)
  51. }
  52. }
  53. return
  54. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/790159
推荐阅读
相关标签
  

闽ICP备14008679号