forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.ts
34 lines (34 loc) · 1002 Bytes
/
Solution.ts
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
function findLadders(beginWord: string, endWord: string, wordList: string[]): string[] {
const ans: string[] = [beginWord];
const vis: boolean[] = Array(wordList.length).fill(false);
const check = (s: string, t: string): boolean => {
if (s.length !== t.length) {
return false;
}
let cnt = 0;
for (let i = 0; i < s.length; ++i) {
if (s[i] !== t[i]) {
++cnt;
}
}
return cnt === 1;
};
const dfs = (s: string): boolean => {
if (s === endWord) {
return true;
}
for (let i = 0; i < wordList.length; ++i) {
const t: string = wordList[i];
if (!vis[i] && check(s, t)) {
vis[i] = true;
ans.push(t);
if (dfs(t)) {
return true;
}
ans.pop();
}
}
return false;
};
return dfs(beginWord) ? ans : [];
}