ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค [lv3] ๋‹จ์–ด๋ณ€ํ™˜ ํŒŒ์ด์ฌ

2021. 4. 25. 14:47ใ†๐Ÿ”ฑ Algorithm/Else

์ •๋ฆฌ

1. ๊ธ€์ž ํ•˜๋‚˜๋งŒ ์ฐจ์ด๋‚˜๋Š” ๋‹จ์–ด๋ฅผ ์ฐพ์•„ ๋ฆฌ์ŠคํŠธ์— append (์ฝ”๋“œ ์ž‘์„ฑ)

2. ์ œํ•œ์‚ฌํ•ญ์—์„œ ๋ฐ์ดํ„ฐ์˜ ๊ธธ์ด๊ฐ€ ๊ธธ์ง€ ์•Š์€ ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค. ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ ์กฐ๊ธˆ ๋†’์•„์ ธ๋„ ํ†ต๊ณผํ•  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ ์‚ผ์ค‘ ๋ฐ˜๋ณต๋ฌธ๋„ try ํ•ด๋ด๋„ ๋œ๋‹ค.

 

- queue๋ฅผ ๋งค๋ฒˆ ์—…๋ฐ์ดํŠธ ํ•ด์ค˜์•ผํ•œ๋‹ค.

- ์™œ๋ƒํ•˜๋ฉด, ์–ด๋–ค ๋‹จ์–ด๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์—ฐ๊ด€๋œ ๋‹จ์–ด๋ฅผ ์ฐพ์„ ๋•Œ๋งˆ๋‹ค queue๊ฐ€ ๋งค๋ฒˆ ๋‹ฌ๋ผ์งˆ ๊ฒƒ์ž„.

- ๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ ์—ฐ๊ด€ ๋‹จ์–ด๋ฅผ ๋‹ด์„ temp_q๋ฅผ ๋งŒ๋“ค์–ด iter๋งˆ๋‹ค ์ดˆ๊ธฐํ™” ํ•ด์ค˜์•ผํ•œ๋‹ค. => ๋‚œ ๊ทธ ์ดˆ๊ธฐํ™” ์ž‘์—…์ด ์—†๋‹ค.

 

์ฃผ์˜ํ•  ์ 

1. ์–ด๋–ค ๋‹จ์–ด์™€ ํ•œ ๊ธ€์ž๋งŒ ์ฐจ์ด๋‚˜๋Š” ๋‹จ์–ด๊ฐ€ ๊ผญ ํ•˜๋‚˜๋ž€ ๋ฒ•์€ ์—†๋‹ค. -> ์—ฌ๋Ÿฌ๊ฐœ์ธ ๊ฒฝ์šฐ๊ฐ€ ๋ถ„๋ช… ์กด์žฌํ•จ์„ ์ธ์ง€

2. tmp_q (์ž„์‹œ queue)์˜ ํ•„์š”์„ฑ์„ ์ธ์ง€ํ•  ๊ฒƒ

 

 

์‹คํŒจํ•œ ํ’€์ด

๋งˆ์ง€๋ง‰ ํ…Œ์ŠคํŠธ์ผ€์ด์Šค์—์„œ ์‹คํŒจ, ๋ชจ๊ฐ€ ๋ฌธ์ œ์ธ์ง€ ์•„์ง ๋ชจ๋ฅด๊ฒ ๋‹ค.

def solution(begin, target, words):
    queue = [begin]
    answer = 0
    while queue:
        tmp_q = []
        curr = queue.pop(0)
        if curr == target:
            return answer

        for i in range(len(words) - 1, -1, -1):
            temp = [1 for a, b in zip(curr, words[i]) if a != b]
            if sum(temp) == 1:
                tmp_q.append(words.pop(i))
                
        answer += 1
        queue = tmp_q

    if not words:
        return 0

 

 

ํ†ต๊ณผํ•œ ์ฝ”๋“œ (๋‹ค๋ฅธ ์‚ฌ๋žŒ ํ’€์ด)

- ์‚ฌ์‹ค ์ด ํ’€์ด๋Š” O(n^3) ์ด๊ธฐ ๋•Œ๋ฌธ์— ๋ณ„๋กœ ๋‚ดํ‚ค์ง€ ์•Š์•˜๋Š”๋ฐ, ์ œํ•œ ์‚ฌํ•ญ์—์„œ words์˜ ๊ธธ์ด๊ฐ€ ์ตœ๋Œ€์ผ ๊ฒฝ์šฐ๊ฐ€ 50 ์ด๊ธฐ์— ์‚ผ์ค‘ ๋ฐ˜๋ณต๋ฌธ๋„ ๊ดœ์ฐฎ๋‹ค.

def solution(begin, target, words):
    answer = 0
    queue = [begin]

    while queue:
        tmp_q = []
        for word1 in queue:
            if word1 == target:
                return answer

            for word2_idx in range(len(words)-1, -1, -1):
                word2 = words[word2_idx]
                difference = sum([x != y for x, y in zip(word1, word2)])
                if difference == 1:
                    tmp_q.append(words.pop(word2_idx))
        if not tmp_q:
            return 0
        queue = tmp_q
        answer += 1

 

- ๋‘ ๋ฒˆ์งธ for๋ฌธ์—์„œ range()๋‚ด๋ถ€ ์ธ์ž๋ฅผ ์ฐจ๊ฐ์‹์œผ๋กœ ์ž‘์„ฑํ•˜์˜€๋Š”๋ฐ, ์ด๋ ‡๊ฒŒ ํ•œ ์ด์œ ๋Š” for๋ฌธ ๋‚ด๋ถ€์—์„œ words๋ฅผ pop()ํ•  ๋•Œ, indexError๋ฅผ ๋ฐฉ์ง€ํ•˜๊ธฐ ์œ„ํ•จ์ด๋‹ค.

 

- word2_idx๋Š” words ๋ฆฌ์ŠคํŠธ์˜ ๋งˆ์ง€๋ง‰ ์ธ๋ฑ์Šค๋ถ€ํ„ฐ ์ฒซ ์ธ๋ฑ์Šค๋กœ ์ฐจ๊ฐ๋˜๊ธฐ ๋•Œ๋ฌธ์—, words.pop(word2_idx)๋ฅผ ํ•  ๋•Œ ๋’ค์—์„œ ๋ถ€ํ„ฐ pop() ํ•  ์ˆ˜ ์žˆ๋‹ค. (์ธ๋ฑ์Šค๊ฐ€ ๊ผฌ์ผ ์œ„ํ—˜ X)