-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path126.dart
More file actions
70 lines (63 loc) · 2.13 KB
/
126.dart
File metadata and controls
70 lines (63 loc) · 2.13 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
import 'dart:collection';
class Solution {
List<List<String>> findLadders(
String beginWord, String endWord, List<String> wordList) {
Map<int, List<int>> wordsGraph = {};
wordList.insert(0, beginWord);
int endWorldIndex = wordList.indexOf(endWord);
if (endWorldIndex == -1) return [];
for (int i = 0; i < wordList.length; i++)
for (int j = i + 1; j < wordList.length; j++) {
if (isSimilarWords(wordList[i], wordList[j])) {
wordsGraph.putIfAbsent(i, () => []).add(j);
wordsGraph.putIfAbsent(j, () => []).add(i);
}
}
List<List<int>> pathGraph = List.generate(wordList.length, (index) => []);
Queue<int> bfsQueue = Queue()..add(0);
Set<int> visited = {};
Set<int> childVisited = {};
while (!bfsQueue.isEmpty) {
childVisited.addAll(bfsQueue);
if (pathGraph[endWorldIndex].length > 0) break;
int queueLen = bfsQueue.length;
for (int i = 0; i < queueLen; i++) {
int nowWord = bfsQueue.removeFirst();
if (visited.contains(nowWord)) continue;
visited.add(nowWord);
bfsQueue.addAll(wordsGraph[nowWord] ?? []);
(wordsGraph[nowWord] ?? []).forEach((index) =>
!childVisited.contains(index) && !visited.contains(index)
? pathGraph[index].add(nowWord)
: null);
}
childVisited.clear();
}
if (pathGraph[endWorldIndex].length == 0) return [];
return buildPath(endWorldIndex, pathGraph, wordList);
}
List<List<String>> buildPath(
int i, List<List<int>> paths, List<String> worlds) {
if (paths[i].length == 0)
return [
[worlds[i]]
];
List<List<String>> res = [];
for (int j = 0; j < paths[i].length; j++) {
for (var element in buildPath(paths[i][j], paths, worlds)) {
res.add(element..add(worlds[i]));
}
}
return res;
}
bool isSimilarWords(String s1, String s2) {
bool oneUnigie = false;
for (int i = 0; i < s1.length; i++) {
if (s1.codeUnitAt(i) != s2.codeUnitAt(i)) {
if (oneUnigie) return false;
oneUnigie = true;
}
}
return oneUnigie;
}
}