From ef99b46cf853a92f3104f366ac07600e7b9756b9 Mon Sep 17 00:00:00 2001 From: Your Name Date: Thu, 18 Jul 2024 02:06:43 -0700 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200110.=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2=E6=8E=A5=E9=BE=99=20BFS=E8=A7=A3=E6=B3=95Java?= =?UTF-8?q?=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/kamacoder/0110.字符串接龙.md | 62 ++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/problems/kamacoder/0110.字符串接龙.md b/problems/kamacoder/0110.字符串接龙.md index 5a60dbb7..feeec6dd 100644 --- a/problems/kamacoder/0110.字符串接龙.md +++ b/problems/kamacoder/0110.字符串接龙.md @@ -153,6 +153,68 @@ int main() { ## 其他语言版本 ### Java +```Java +public class Main { + // BFS方法 + public static int ladderLength(String beginWord, String endWord, List wordList) { + // 使用set作为查询容器,效率更高 + HashSet set = new HashSet<>(wordList); + + // 声明一个queue存储每次变更一个字符得到的且存在于容器中的新字符串 + Queue queue = new LinkedList<>(); + + // 声明一个hashMap存储遍历到的字符串以及所走过的路径path + HashMap visitMap = new HashMap<>(); + queue.offer(beginWord); + visitMap.put(beginWord, 1); + + while (!queue.isEmpty()) { + String curWord = queue.poll(); + int path = visitMap.get(curWord); + + for (int i = 0; i < curWord.length(); i++) { + char[] ch = curWord.toCharArray(); + // 每个位置尝试26个字母 + for (char k = 'a'; k <= 'z'; k++) { + ch[i] = k; + + String newWord = new String(ch); + if (newWord.equals(endWord)) return path + 1; + + // 如果这个新字符串存在于容器且之前未被访问到 + if (set.contains(newWord) && !visitMap.containsKey(newWord)) { + visitMap.put(newWord, path + 1); + queue.offer(newWord); + } + } + } + } + + return 0; + } + + public static void main (String[] args) { + /* code */ + // 接收输入 + Scanner sc = new Scanner(System.in); + int N = sc.nextInt(); + sc.nextLine(); + String[] strs = sc.nextLine().split(" "); + + List wordList = new ArrayList<>(); + for (int i = 0; i < N; i++) { + wordList.add(sc.nextLine()); + } + + // wordList.add(strs[1]); + + // 打印结果 + int result = ladderLength(strs[0], strs[1], wordList); + System.out.println(result); + } +} + +``` ### Python