79.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package main
  2. // Pos stands for the position of board[y][x]
  3. type Pos struct {
  4. x int
  5. y int
  6. }
  7. func existIter(board [][]byte, word string, visited map[Pos]struct{}, last Pos) bool {
  8. if _, ok := visited[last]; ok {
  9. return false
  10. }
  11. if len(word) == 0 {
  12. return true
  13. }
  14. visited[last] = struct{}{}
  15. for dir := 0; dir < 4; dir++ {
  16. var pos Pos
  17. switch dir {
  18. case 0: // up
  19. if last.y > 0 && board[last.y-1][last.x] == word[0] {
  20. pos = Pos{last.x, last.y - 1}
  21. } else {
  22. continue
  23. }
  24. case 1: // down
  25. if last.y < len(board)-1 && board[last.y+1][last.x] == word[0] {
  26. pos = Pos{last.x, last.y + 1}
  27. } else {
  28. continue
  29. }
  30. case 2: // left
  31. if last.x > 0 && board[last.y][last.x-1] == word[0] {
  32. pos = Pos{last.x - 1, last.y}
  33. } else {
  34. continue
  35. }
  36. default: // right
  37. if last.x < len(board[0])-1 && board[last.y][last.x+1] == word[0] {
  38. pos = Pos{last.x + 1, last.y}
  39. } else {
  40. return false
  41. }
  42. }
  43. newMap := make(map[Pos]struct{})
  44. for k := range visited {
  45. newMap[k] = struct{}{}
  46. }
  47. if existIter(board, word[1:], newMap, pos) {
  48. return true
  49. }
  50. }
  51. return false
  52. }
  53. // too complex and slow
  54. func existOld(board [][]byte, word string) bool {
  55. beg := word[0]
  56. for y, row := range board {
  57. for x, v := range row {
  58. if beg == v && existIter(board, word[1:], map[Pos]struct{}{}, Pos{x, y}) {
  59. return true
  60. }
  61. }
  62. }
  63. return false
  64. }
  65. func exist(board [][]byte, word string) bool {
  66. return false
  67. }
  68. /* func main() {
  69. b1 := [][]byte{
  70. {'A', 'B', 'C', 'E'},
  71. {'S', 'F', 'C', 'S'},
  72. {'A', 'D', 'E', 'E'},
  73. }
  74. fmt.Println(exist(b1, "ABCCED"))
  75. fmt.Println(exist(b1, "SEE"))
  76. fmt.Println(exist(b1, "ABCB"))
  77. fmt.Println(exist(b1, "FSADEESCCBA"))
  78. fmt.Println(exist(b1, "ZSADEESCCBA"))
  79. } */