79.go 1.7 KB

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