작심삼일

[LeetCode] 433 | Minimum Genetic Mutation | Python 본문

스터디/코테

[LeetCode] 433 | Minimum Genetic Mutation | Python

yun_s 2022. 11. 2. 09:10
728x90
반응형

문제 링크: https://leetcode.com/problems/minimum-genetic-mutation/


문제

A gene string can be represented by an 8-character long string, with choices from 'A', 'C', 'G', and 'T'.

Suppose we need to investigate a mutation from a gene string start to a gene string end where one mutation is defined as one single character changed in the gene string.

  • For example, "AACCGGTT" --> "AACCGGTA" is one mutation.

There is also a gene bank bank that records all the valid gene mutations. A gene must be in bank to make it a valid gene string.

Given the two gene strings start and end and the gene bank bank, return the minimum number of mutations needed to mutate from start to end. If there is no such a mutation, return -1.

Note that the starting point is assumed to be valid, so it might not be included in the bank.


조건

  • start.length == 8
  • end.length == 8
  • 0 <= bank.length <= 10
  • bank[i].length == 8
  • start, end, and bank[i] consist of only the characters ['A', 'C', 'G', 'T'].

내 풀이

queue를 이용한다.

start의 모든 글자를 차례대로 ACGT로 바꿔서 mutate를 실행하며, mutated 글자가 bank 안에 존재하면 이를 queue에 추가한다.


코드

class Solution:
    def minMutation(self, start: str, end: str, bank: List[str]) -> int:
        queue = [(start, 0)]
        
        while queue:
            gene, number = queue.pop(0)
            
            if gene == end:
                return number
            
            for i in range(len(gene)):
                for ch in "ACGT":
                    mutated = gene[:i] + ch + gene[i+1:]
                    
                    if mutated in bank:
                        bank.remove(mutated)
                        queue.append((mutated, number+1))
        
        return -1
728x90
반응형
Comments