Skip to content

Commit 31fb661

Browse files
author
Eric
committed
104차 3번 문제풀이
1 parent 0c053cf commit 31fb661

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
function solution(begin, target, words) {
2+
if (!words.includes(target)) return 0;
3+
4+
const queue = [[begin, 0]];
5+
const visited = new Set();
6+
7+
function canTransform(word1, word2) {
8+
let diffCount = 0;
9+
10+
for (let i = 0; i < word1.length; i++) {
11+
if (word1[i] !== word2[i]) diffCount++;
12+
if (diffCount > 1) return false;
13+
}
14+
15+
return diffCount === 1;
16+
}
17+
18+
while (queue.length) {
19+
const [current, count] = queue.shift();
20+
21+
if (current === target) return count;
22+
23+
for (const word of words) {
24+
if (!visited.has(word) && canTransform(current, word)) {
25+
visited.add(word);
26+
queue.push([word, count + 1]);
27+
}
28+
}
29+
}
30+
31+
return 0;
32+
}
33+
34+
console.log(solution('hit', 'cog', ['hot', 'lot', 'dog', 'dot', 'log', 'cog']));

0 commit comments

Comments
 (0)