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

Chobbyยท2022๋…„ 3์›” 12์ผ
0

Programmers

๋ชฉ๋ก ๋ณด๊ธฐ
12/349

๋ฌธ์ œ ์„ค๋ช…

๋‘ ๊ฐœ์˜ ๋‹จ์–ด begin, target๊ณผ ๋‹จ์–ด์˜ ์ง‘ํ•ฉ words๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. ์•„๋ž˜์™€ ๊ฐ™์€ ๊ทœ์น™์„ ์ด์šฉํ•˜์—ฌ begin์—์„œ target์œผ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ๊ฐ€์žฅ ์งง์€ ๋ณ€ํ™˜ ๊ณผ์ •์„ ์ฐพ์œผ๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค.

1. ํ•œ ๋ฒˆ์— ํ•œ ๊ฐœ์˜ ์•ŒํŒŒ๋ฒณ๋งŒ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
2. words์— ์žˆ๋Š” ๋‹จ์–ด๋กœ๋งŒ ๋ณ€ํ™˜ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด begin์ด "hit", target๊ฐ€ "cog", words๊ฐ€ ["hot","dot","dog","lot","log","cog"]๋ผ๋ฉด "hit" -> "hot" -> "dot" -> "dog" -> "cog"์™€ ๊ฐ™์ด 4๋‹จ๊ณ„๋ฅผ ๊ฑฐ์ณ ๋ณ€ํ™˜ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

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

์ œํ•œ์‚ฌํ•ญ

๊ฐ ๋‹จ์–ด๋Š” ์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž๋กœ๋งŒ ์ด๋ฃจ์–ด์ ธ ์žˆ์Šต๋‹ˆ๋‹ค.
๊ฐ ๋‹จ์–ด์˜ ๊ธธ์ด๋Š” 3 ์ด์ƒ 10 ์ดํ•˜์ด๋ฉฐ ๋ชจ๋“  ๋‹จ์–ด์˜ ๊ธธ์ด๋Š” ๊ฐ™์Šต๋‹ˆ๋‹ค.
words์—๋Š” 3๊ฐœ ์ด์ƒ 50๊ฐœ ์ดํ•˜์˜ ๋‹จ์–ด๊ฐ€ ์žˆ์œผ๋ฉฐ ์ค‘๋ณต๋˜๋Š” ๋‹จ์–ด๋Š” ์—†์Šต๋‹ˆ๋‹ค.
begin๊ณผ target์€ ๊ฐ™์ง€ ์•Š์Šต๋‹ˆ๋‹ค.
๋ณ€ํ™˜ํ•  ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ์—๋Š” 0๋ฅผ return ํ•ฉ๋‹ˆ๋‹ค.

์ž…์ถœ๋ ฅ ์˜ˆ

์ž…์ถœ๋ ฅ ์˜ˆ ์„ค๋ช…

์˜ˆ์ œ #1
๋ฌธ์ œ์— ๋‚˜์˜จ ์˜ˆ์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

์˜ˆ์ œ #2
target์ธ "cog"๋Š” words ์•ˆ์— ์—†๊ธฐ ๋•Œ๋ฌธ์— ๋ณ€ํ™˜ํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.

๋‚˜์˜ ์ฝ”๋“œ

function solution(begin, target, words) {
    debugger
    function bfs() {
        const queue = [begin]
        const visit = [begin]
        let count = 0
        while(queue.length) {
            const cur = queue.pop()
            // ํ˜„์žฌ ๋‹จ์–ด์™€ ๋‹ค๋ฅธ ์ŠคํŽ ๋ง์ด 1๊ฐœ์ธ ๋‹จ์–ด๋ฅผ ํ์— push
            words.forEach(word => {
                if(!visit.includes(word)) {
                    let diff = 0
                    // ์ŠคํŽ ๋ง์ด ํ•˜๋‚˜ ๋‹ค๋ฅธ๊ฒƒ๋“ค์„ ์ฒดํฌ
                    for(let i = 0 ; i < word.length ; i ++) {
                        if(cur[i] !== word[i]) {
                            diff++
                        }
                    }
                    // ๋ชฉํ‘œ ๋‹จ์–ด์ธ์ง€ ํ™•์ธ
                    if(diff === 1) {
                        if(target === word && diff === 1) {
                            return count+1
                        } else {
                            queue.push(word)
                            visit.push(word)
                        }
                    }    
                } 
            })
            count++
        }
        return count
    }
    
    // ๋ณ€ํ™˜์ด ๊ฐ€๋Šฅํ•œ์ง€ ์ฒดํฌ
    if(words.includes(target)) {
        return bfs()
    } else {
        return 0
    }
}

์ค‘์š”ํ•œ ํฌ์ธํŠธ๋Š” ํ˜„์žฌ ๋‹จ์–ด์™€ ๋‹ค๋ฅธ ์ŠคํŽ ๋ง์ด 1๊ฐœ์ธ ๋‹จ์–ด๋ฅผ ํ์— push ํ•˜๋Š” ๊ฒƒ ์ด๋‹ค.

profile
๋‚ด ์ง€์‹์„ ๊ณต์œ ํ•  ์ˆ˜ ์žˆ๋Š” ๋Œ€๋‹ดํ•จ

0๊ฐœ์˜ ๋Œ“๊ธ€