From 7df04d99299c154b66c9680f9212e8ccf6b7fe61 Mon Sep 17 00:00:00 2001 From: lylain Date: Sun, 30 Mar 2025 09:58:39 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=AD=97=E7=AC=A6=E4=B8=B2?= =?UTF-8?q?=E6=8E=A5=E9=BE=99go=E8=AF=AD=E8=A8=80=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/kamacoder/0110.字符串接龙.md | 76 +++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/problems/kamacoder/0110.字符串接龙.md b/problems/kamacoder/0110.字符串接龙.md index af343690..c803a922 100644 --- a/problems/kamacoder/0110.字符串接龙.md +++ b/problems/kamacoder/0110.字符串接龙.md @@ -268,6 +268,82 @@ if __name__=='__main__': ### Go +```go +package main + +import ( + "bufio" + "fmt" + "os" + "strconv" + "strings" +) + +func connectWord(words []string, startWord string, endWord string) int { + if words == nil || len(words) == 0 { + return 0 + } + var allWord = make(map[string]bool) + for _, word := range words { + allWord[word] = true + } + visitedWord := make(map[string]bool) + queue := make([]string, 0) + result := 1 + queue = append(queue, startWord) + queue = append(queue, "") + for len(queue) > 0 { + word := queue[0] + queue = queue[1:] + if word == "" { + if len(queue) > 0 { + result++ + queue = append(queue, "") + } + continue + } + arr := []rune(word) + for i := 0; i < len(arr); i++ { + old := arr[i] + for j := 'a'; j <= 'z'; j++ { + arr[i] = j + newWord := string(arr) + if allWord[newWord] && !visitedWord[newWord] { + visitedWord[newWord] = true + queue = append(queue, newWord) + if newWord == endWord { + return result + 1 + } + } + } + arr[i] = old + } + } + return 0 +} + +func main() { + scanner := bufio.NewScanner(os.Stdin) + scanner.Scan() + n, _ := strconv.Atoi(scanner.Text()) + scanner.Scan() + input := strings.Split(scanner.Text(), " ") + beginStr := input[0] + endStr := input[1] + + wordList := []string{beginStr, endStr} + for i := 0; i < n; i++ { + scanner.Scan() + wordList = append(wordList, scanner.Text()) + } + count := connectWord(wordList, beginStr, endStr) + fmt.Println(count) +} + +``` + + + ### Rust ### JavaScript