Skip to content

Commit d14ac90

Browse files
committed
[leet] word ladder 다시 품 (hard)
1 parent 558c154 commit d14ac90

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

허현빈/5주차/260129-1.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,4 @@ var ladderLength = function (beginWord, endWord, wordList) {
3737
return ans;
3838
};
3939
//시간복잡도 터짐 실패
40+
//20분정도 푼듯

허현빈/5주차/260129-2.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* @param {string} beginWord
3+
* @param {string} endWord
4+
* @param {string[]} wordList
5+
* @return {number}
6+
*/
7+
var ladderLength = function (beginWord, endWord, wordList) {
8+
const matches = (word1, word2) => {
9+
let count = 0;
10+
for (let j = 0; j < word1.length; j++) {
11+
if (word1[j] !== word2[j]) {
12+
count++;
13+
if (count >= 2) return false;
14+
}
15+
}
16+
return count === 1;
17+
};
18+
19+
let finalAns = Infinity;
20+
21+
const bfs = (startWord, startIdx) => {
22+
const q = [[startWord, 2]];
23+
const visit = Array.from({ length: wordList.length }).fill(false);
24+
visit[startIdx] = true;
25+
26+
while (q.length > 0) {
27+
const [cur, ladderCount] = q.shift();
28+
29+
if (cur === endWord) {
30+
finalAns = Math.min(finalAns, ladderCount);
31+
}
32+
33+
for (let i = 0; i < wordList.length; i++) {
34+
if (!visit[i] && matches(cur, wordList[i])) {
35+
visit[i] = true;
36+
q.push([wordList[i], ladderCount + 1]);
37+
}
38+
}
39+
}
40+
};
41+
42+
for (let i = 0; i < wordList.length; i++) {
43+
if (matches(beginWord, wordList[i])) {
44+
bfs(wordList[i], i);
45+
}
46+
}
47+
48+
return finalAns === Infinity ? 0 : finalAns;
49+
};
50+
// bfs로 다시품 정답
51+
// 10분젇도 더 쓴듯

0 commit comments

Comments
 (0)