MCPcopy Create free account
hub / github.com/EndlessCheng/codeforces-go / ladderLength

Function ladderLength

leetcode/main.go:597–676  ·  view source on GitHub ↗

LC 127 双向 BFS

(beginWord string, endWord string, wordList []string)

Source from the content-addressed store, hash-verified

595
596// LC 127 双向 BFS
597func ladderLength(beginWord string, endWord string, wordList []string) int {
598 wid := map[string]int{}
599 g := [][]int{}
600 addWord := func(w string) int {
601 id, has := wid[w]
602 if !has {
603 id = len(wid)
604 wid[w] = id
605 g = append(g, []int{})
606 }
607 return id
608 }
609 addEdge := func(w string) int {
610 id1 := addWord(w)
611 s := []byte(w)
612 for i, b := range s {
613 s[i] = '*'
614 id2 := addWord(string(s))
615 g[id1] = append(g[id1], id2)
616 g[id2] = append(g[id2], id1)
617 s[i] = b
618 }
619 return id1
620 }
621
622 for _, w := range wordList {
623 addEdge(w)
624 }
625 st := addEdge(beginWord)
626 end, has := wid[endWord]
627 if !has {
628 return 0
629 }
630
631 const inf int = 1e9
632 dst := make([]int, len(wid))
633 for i := range dst {
634 dst[i] = inf
635 }
636 dst[st] = 0
637 qst := []int{st}
638
639 dend := make([]int, len(wid))
640 for i := range dend {
641 dend[i] = inf
642 }
643 dend[end] = 0
644 qend := []int{end}
645
646 for len(qst) > 0 && len(qend) > 0 {
647 q := qst
648 qst = nil
649 for _, v := range q {
650 if dend[v] < inf {
651 return (dst[v]+dend[v])/2 + 1
652 }
653 for _, w := range g[v] {
654 if dst[w] == inf {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected