GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/src/WordLadder.java at master · LeBW/leetcode

Expand file tree

/

WordLadder.java

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
58 lines (56 loc) · 2.1 KB
/

WordLadder.java

Copy path

File metadata and controls

58 lines (56 loc) · 2.1 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.util.*;
/**
* 127. Word Ladder
* 广度优先搜索。
* 将word看作节点,不同节点间如果只相差一个字母,则用边相连。
* 最后的问题就是找到beginWord和endWord之间的最短路径(利用BFS).
* 注意:这里不需要提前建图,只需要在遍历到某个word的时候,计算它与其他节点的距离,找到相邻节点即可。
* 注意:在记录已经访问过的节点时,使用下表索引数组boolean[] isVisited 比 使用单词哈希表 Set<String> 快很多。
* @author LBW
*/
public class WordLadder {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
// BFS
Queue<String> queue = new ArrayDeque<>();
queue.add(beginWord);
// Set<String> isVisited = new HashSet<>();
// isVisited.add(beginWord);
boolean[] isVisited = new boolean[wordList.size()];
int idx = wordList.indexOf(beginWord);
if (idx != -1) {
isVisited[idx] = true;
}
int step = 1;
while (!queue.isEmpty()) {
int size = queue.size();
step += 1;
for (int i = 0; i < size; i++) {
String word = queue.poll();
// 找到所有与word只差一个字母的单词
for (int j = 0; j < wordList.size(); j++) {
String w = wordList.get(j);
if (!isVisited[j] && isDifferentOnlyOneLetter(w, word)) {
queue.add(w);
isVisited[j] = true;
if (w.equals(endWord)) {
return step;
}
}
}
}
}
return 0;
}
private boolean isDifferentOnlyOneLetter(String word1, String word2) {
int n = word1.length();
int count = 0;
for (int i = 0; i < n; i++) {
if (word1.charAt(i) != word2.charAt(i)) {
count += 1;
if (count > 1)
return false;
}
}
return count == 1;
}
}
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.