@@ -268,6 +268,82 @@ if __name__=='__main__':
268268
269269### Go
270270
271+ ``` go
272+ package main
273+
274+ import (
275+ " bufio"
276+ " fmt"
277+ " os"
278+ " strconv"
279+ " strings"
280+ )
281+
282+ func connectWord (words []string , startWord string , endWord string ) int {
283+ if words == nil || len (words) == 0 {
284+ return 0
285+ }
286+ var allWord = make (map [string ]bool )
287+ for _ , word := range words {
288+ allWord[word] = true
289+ }
290+ visitedWord := make (map [string ]bool )
291+ queue := make ([]string , 0 )
292+ result := 1
293+ queue = append (queue, startWord)
294+ queue = append (queue, " " )
295+ for len (queue) > 0 {
296+ word := queue[0 ]
297+ queue = queue[1 :]
298+ if word == " " {
299+ if len (queue) > 0 {
300+ result++
301+ queue = append (queue, " " )
302+ }
303+ continue
304+ }
305+ arr := []rune (word)
306+ for i := 0 ; i < len (arr); i++ {
307+ old := arr[i]
308+ for j := ' a' ; j <= ' z' ; j++ {
309+ arr[i] = j
310+ newWord := string (arr)
311+ if allWord[newWord] && !visitedWord[newWord] {
312+ visitedWord[newWord] = true
313+ queue = append (queue, newWord)
314+ if newWord == endWord {
315+ return result + 1
316+ }
317+ }
318+ }
319+ arr[i] = old
320+ }
321+ }
322+ return 0
323+ }
324+
325+ func main () {
326+ scanner := bufio.NewScanner (os.Stdin )
327+ scanner.Scan ()
328+ n , _ := strconv.Atoi (scanner.Text ())
329+ scanner.Scan ()
330+ input := strings.Split (scanner.Text (), " " )
331+ beginStr := input[0 ]
332+ endStr := input[1 ]
333+
334+ wordList := []string {beginStr, endStr}
335+ for i := 0 ; i < n; i++ {
336+ scanner.Scan ()
337+ wordList = append (wordList, scanner.Text ())
338+ }
339+ count := connectWord (wordList, beginStr, endStr)
340+ fmt.Println (count)
341+ }
342+
343+ ```
344+
345+
346+
271347### Rust
272348
273349### JavaScript
0 commit comments