๋ฐ์ํ
๐ค๋ฌธ์ ํด๊ฒฐ
-
Lv3 | BFS
- begin ์์ ์์ํ์ฌ BFS ํ์
- BFS๋ target๊ณผ์ ๊ฑฐ๋ฆฌ๋ฅผ ์ ์ ์์ผ๋ฏ๋ก
- target๊ณผ์ ์ต๋จ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํด์ ๋ต์ ์ถ๋ ฅ
- ์๋์ ์ฝ๋์์๋ visited์ words_obj๋ฅผ ์ฌ์ฉํ์ง๋ง
์ ์ง๋ณด๋ฉด words_obj ํ๋๋ก ์ถฉ๋ถํ ๊ตฌํํ ์ ์๋ค!
๐ป์์ค ์ฝ๋
function solution(begin, target, words) {
var answer = 0;
// ํ๊ฒ์ด ์๋์ ์๋ ๊ฒฝ์ฐ
if (!words.includes(target)) {
return answer
}
let n = words.length
// visited ์ queue
let visited = Array(n).fill(0)
let q = [begin]
// ๋จ์ด์ ์ธ๋ฑ์ค๋ฅผ ๊ฐ์ฒด์ ์ ์ฅ
const words_obj = {}
for (let i in words) {
words_obj[words[i]] = i
}
while (q.length > 0) {
let c = q.shift()
// ํ๊ฒ ์๋์ ๋๋ฌํ๋ฉด ๋
if (c == target) {
return visited[words_obj[c]]
}
for (let i in words) {
if (visited[i] == 0) {
let word = words[i]
let diff = 0
for (let j in word) {
if (c[j] != word[j]) {
diff++
}
if (diff > 1) {
break
}
}
if (diff == 1) {
q.push(word)
if (c == begin) {
visited[i] = 1
} else {
visited[i] = visited[words_obj[c]] + 1
}
}
}
}
}
console.log(visited)
return answer;
}
๐๋ฌธ์ ํ์ธ
์ถ์ฒ: ํ๋ก๊ทธ๋๋จธ์ค
๋งํฌ: https://programmers.co.kr/learn/courses/30/lessons/43163
๋ฐ์ํ