๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿบ ๋งค์ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ๋‹จ์–ด ๋ณ€ํ™˜

๋ฌธ์ œํ’€์ด์— ๋ฐฑํŠธ๋ž˜ํ‚น์„ ์ ์šฉํ•˜์˜€๊ณ , ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๋กœ ์ž‘์„ฑํ–ˆ์Šต๋‹ˆ๋‹ค.

 

 

๋ฌธ์ œ

๋‘ ๊ฐœ์˜ ๋‹จ์–ด begin, target๊ณผ ๋‹จ์–ด ์ง‘ํ•ฉ words๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, ์ตœ์†Œ ๋ช‡ ๋‹จ๊ณ„๋ฅผ ๊ฑฐ์ณ begin์ด target์œผ๋กœ ๋ณ€ํ™˜ ๋  ์ˆ˜ ์žˆ๋Š”์ง€๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋ผ.

 

์ œํ•œ์‚ฌํ•ญ

  • ํ•œ ๋ฒˆ์— ํ•œ ๊ฐœ์˜ ์•ŒํŒŒ๋ฒณ๋งŒ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ๋‹ค.
  • words์— ์žˆ๋Š” ๋‹จ์–ด๋กœ๋งŒ ๋ณ€ํ™˜ํ•  ์ˆ˜ ์žˆ๋‹ค.
  • ๊ฐ ๋‹จ์–ด๋Š” ์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž๋กœ๋งŒ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค.
  • 3 <= ๊ฐ ๋‹จ์–ด์˜ ๊ธธ์ด <= 10
  • begin !== target
  • ๋ณ€ํ™˜ํ•  ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ 0์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

์˜ˆ์ œ

 

begin: hit

target: cog

words: [hot,dot,dog,lot,log,cog]

 

hit->hot->dot->dog->cog์™€ ๊ฐ™์ด 4๋‹จ๊ณ„๋ฅผ ๊ฑฐ์ณ ๋ณ€ํ™˜ ๊ฐ€๋Šฅ.

 

 

 

๋ฌธ์ œํ’€์ด

 

์ด ๋ฌธ์ œ์˜ ๊ฐ€์žฅ ์ž‘์€ ํ•˜์œ„๋ฌธ์ œ๋Š” words ์ˆœํšŒํ•  ๋•Œ ์ด์ „ ๋ฌธ์ž์—ด์„ ํ˜„์žฌ ๋ฌธ์ž์—ด์œผ๋กœ ์ˆ˜์ •ํ•  ์ˆ˜ ์žˆ๋Š”๊ฐ€ ์—†๋Š”๊ฐ€ ์ด๋‹ค. ์ˆ˜์ •์ด ๊ฐ€๋Šฅํ•  ๊ฒฝ์šฐ ์ด์ „๋ฌธ์ž์—ด์„ ํ˜„์žฌ ๋ฌธ์ž์—ด๋กœ ์ˆ˜์ •ํ•œ ๊ฒฝ์šฐ์™€ ์ˆ˜์ •ํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ ๋‘˜ ๋‹ค ํƒ์ƒ‰ํ•ด์•ผํ•œ๋‹ค. ์ˆ˜์ •์ด ๋ถˆ๊ฐ€๋Šฅํ•œ ๊ฒฝ์šฐ ์ˆ˜์ •ํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ๋งŒ ํƒ์ƒ‰ํ•œ๋‹ค.

 

function solution(begin, target, words) {
    let minAns = Infinity
    const getDiff = (a, b) => a.split("").reduce((cnt, e, j) => cnt + (e !== b[j]), 0)
    const backtrack = (i, x, n, visited) => {
        if (x === target) {
            minAns = Math.min(n, minAns)
        }
        visited.add(x)
        if (i < words.length) {
            if (getDiff(x, words[i]) === 1 && !visited.has(words[i])) {
                backtrack(0, words[i], n+1, visited)
            }
            backtrack(i+1, x, n, visited)
        }
        visited.delete(x)
    }
    backtrack(0, begin, 0, new Set([begin]))
    return minAns > words.length ? 0 : minAns
}

 

์‹œ๊ฐ„๋ณต์žก๋„: O(n! * n)

๊ณต๊ฐ„๋ณต์žก๋„: O(n)