-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution_126.java
More file actions
79 lines (73 loc) · 2 KB
/
Solution_126.java
File metadata and controls
79 lines (73 loc) · 2 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
package com.hilbert25.leetcode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
/**
* @author : hilbert25
* @version 创建时间:2017年5月16日 上午12:38:57 LeetCode com.hilbert25.leetcode
* Solution_126
*/
public class Solution_126 {
public static void main(String[] args) {
}
public static int minLongest = Integer.MAX_VALUE;
/**
* dfs or backtracking will be ttl,so choose bfs
*
* @param beginWord
* @param endWord
* @param wordList
* @return
*/
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
List<List<String>> res = new ArrayList<List<String>>();
List<String> curList = new ArrayList<String>();
Map<String, List<String>> map = new HashMap<String, List<String>>();
if (!wordList.contains(beginWord)) {
wordList.add(beginWord);
}
if (!wordList.contains(endWord)) {
wordList.add(endWord);
}
boolean[] visited = new boolean[wordList.size()];
visited[wordList.indexOf(beginWord)] = true;
Queue<Integer> queue = new LinkedList<Integer>();
queue.add(wordList.indexOf(beginWord));
List<String> list = new ArrayList<>();
list.add(beginWord);
map.put(beginWord, list);
while (!queue.isEmpty()) {
int count = queue.size();
for (int i = 0; i < count; i++) {
int t = queue.poll();
for (int j = 0; j < count; j++) {
if (!visited[t] && isNeighbour(wordList.get(i), wordList.get(j))) {
queue.offer(j);
List<String> tempList = new ArrayList<String>(map.get(wordList.get(t)));
tempList.add(wordList.get(j));
map.put(wordList.get(j), tempList);
visited[j] = true;
}
}
}
}
return res;
}
/**
* @param word1
* @param word2
* @return
*/
public boolean isNeighbour(String word1, String word2) {
int count = 0;
for (int i = 0; i < word1.length(); i++) {
if (word1.charAt(i) != word2.charAt(i)) {
count++;
}
}
return count == 1;
}
}