127.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package main
  2. // begin & end are non-empty and not the same
  3. func ladderLength(beginWord string, endWord string, wordList []string) int {
  4. wordCnt := len(wordList)
  5. if wordCnt == 0 {
  6. return 0
  7. }
  8. target := -1
  9. for i := 0; i < wordCnt; i++ {
  10. if wordList[i] == endWord {
  11. target = i
  12. break
  13. }
  14. }
  15. if target == -1 {
  16. return 0
  17. }
  18. newList := append(wordList, beginWord)
  19. distance := make([]int, wordCnt+1)
  20. distance[wordCnt] = 1 // Initial ladder length: 1
  21. isMin := make([]bool, wordCnt+1)
  22. queue := make([]int, 0)
  23. queue = append(queue, wordCnt)
  24. for len(queue) != 0 { // Dijkstra method
  25. newQueue := make([]int, 0)
  26. for len(queue) != 0 {
  27. idx := queue[0]
  28. queue = queue[1:] // Dequeue
  29. for i := 0; i < wordCnt; i++ {
  30. if !isMin[i] {
  31. if isConvertible(newList[idx], newList[i]) &&
  32. (distance[i] == 0 || distance[idx] < distance[i]) {
  33. distance[i] = distance[idx] + 1
  34. }
  35. if len(queue) == 0 && distance[i] != 0 {
  36. newQueue = append(newQueue, i)
  37. isMin[i] = true
  38. }
  39. }
  40. }
  41. }
  42. queue = newQueue
  43. }
  44. return distance[target]
  45. }
  46. func isConvertible(src, dst string) bool {
  47. diff := 0
  48. for i := 0; i < len(src); i++ {
  49. if src[i] != dst[i] {
  50. diff++
  51. }
  52. }
  53. return diff == 1
  54. }
  55. // func main() {
  56. // wordList := []string{"hot", "dot", "dog", "lot", "log", "cog"}
  57. // println(ladderLength("dog", "but", wordList))
  58. // println(ladderLength("hit", "cog", wordList))
  59. // }