@@ -153,6 +153,68 @@ int main() {
153
153
## 其他语言版本
154
154
155
155
### Java
156
+ ``` Java
157
+ public class Main {
158
+ // BFS方法
159
+ public static int ladderLength (String beginWord , String endWord , List<String > wordList ) {
160
+ // 使用set作为查询容器,效率更高
161
+ HashSet<String > set = new HashSet<> (wordList);
162
+
163
+ // 声明一个queue存储每次变更一个字符得到的且存在于容器中的新字符串
164
+ Queue<String > queue = new LinkedList<> ();
165
+
166
+ // 声明一个hashMap存储遍历到的字符串以及所走过的路径path
167
+ HashMap<String , Integer > visitMap = new HashMap<> ();
168
+ queue. offer(beginWord);
169
+ visitMap. put(beginWord, 1 );
170
+
171
+ while (! queue. isEmpty()) {
172
+ String curWord = queue. poll();
173
+ int path = visitMap. get(curWord);
174
+
175
+ for (int i = 0 ; i < curWord. length(); i++ ) {
176
+ char [] ch = curWord. toCharArray();
177
+ // 每个位置尝试26个字母
178
+ for (char k = ' a' ; k <= ' z' ; k++ ) {
179
+ ch[i] = k;
180
+
181
+ String newWord = new String (ch);
182
+ if (newWord. equals(endWord)) return path + 1 ;
183
+
184
+ // 如果这个新字符串存在于容器且之前未被访问到
185
+ if (set. contains(newWord) && ! visitMap. containsKey(newWord)) {
186
+ visitMap. put(newWord, path + 1 );
187
+ queue. offer(newWord);
188
+ }
189
+ }
190
+ }
191
+ }
192
+
193
+ return 0 ;
194
+ }
195
+
196
+ public static void main (String [] args ) {
197
+ /* code */
198
+ // 接收输入
199
+ Scanner sc = new Scanner (System . in);
200
+ int N = sc. nextInt();
201
+ sc. nextLine();
202
+ String [] strs = sc. nextLine(). split(" " );
203
+
204
+ List<String > wordList = new ArrayList<> ();
205
+ for (int i = 0 ; i < N ; i++ ) {
206
+ wordList. add(sc. nextLine());
207
+ }
208
+
209
+ // wordList.add(strs[1]);
210
+
211
+ // 打印结果
212
+ int result = ladderLength(strs[0 ], strs[1 ], wordList);
213
+ System . out. println(result);
214
+ }
215
+ }
216
+
217
+ ```
156
218
157
219
### Python
158
220
0 commit comments