-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution_127.java
More file actions
87 lines (82 loc) · 1.75 KB
/
Solution_127.java
File metadata and controls
87 lines (82 loc) · 1.75 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
*
*/
/**
* @author 作者 : hht
* @version 创建时间:2017年7月3日 下午9:41:42
* 类说明
*/
/**
* @author hht
*
*/
public class Solution_127 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
/**
* @param beginWord
* @param endWord
* @param wordList
* @return
*/
public int ladderLength(String beginWord, String endWord,
List<String> wordList) {
if (!wordList.contains(endWord))
return 0;
boolean[][] neighbour = new boolean[wordList.size()][wordList.size()];
boolean[] visited = new boolean[wordList.size()];
for (int i = 0; i < wordList.size(); i++) {
for (int j = i + 1; j < wordList.size(); j++) {
neighbour[i][j] = isNeigh(wordList.get(i), wordList.get(j));
neighbour[j][i] = neighbour[i][j];
}
}
Queue<Integer> queue = new LinkedList<Integer>();
int level = 1;
for (int i = 0; i < wordList.size(); i++) {
if (isNeigh(beginWord, wordList.get(i))) {
if (wordList.get(i).equals(endWord))
return 2;
visited[i] = true;
queue.add(i);
}
}
while (!queue.isEmpty()) {
int count = queue.size();
level++;
for (int i = 0; i < count; i++) {
int t = queue.poll();
if (wordList.get(t).equals(endWord)) {
return level;
}
for (int j = 0; j < wordList.size(); j++) {
if (neighbour[t][j] && !visited[j]) {
queue.add(j);
}
}
}
}
return level;
}
/**
* @param str1
* @param str2
* @return
*/
public boolean isNeigh(String str1, String str2) {
int count = 0;
for (int i = 0; i < str1.length(); i++) {
if (str1.charAt(i) != str2.charAt(i)) {
count++;
}
}
return count == 1;
}
}