엔지니어 게시판
LeetCode 솔루션 분류

[11/2] 433. Minimum Genetic Mutation

컨텐츠 정보

본문

Medium
1813185Add to ListShare

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.

 

Example 1:

Input: start = "AACCGGTT", end = "AACCGGTA", bank = ["AACCGGTA"]
Output: 1

Example 2:

Input: start = "AACCGGTT", end = "AAACGGTA", bank = ["AACCGGTA","AACCGCTA","AAACGGTA"]
Output: 2

Example 3:

Input: start = "AAAAACCC", end = "AACCCCCC", bank = ["AAAACCCC","AAACCCCC","AACCCCCC"]
Output: 3

 

Constraints:

  • start.length == 8
  • end.length == 8
  • 0 <= bank.length <= 10
  • bank[i].length == 8
  • startend, and bank[i] consist of only the characters ['A', 'C', 'G', 'T'].
Accepted
85,816
Submissions
170,100
태그

관련자료

댓글 1

학부유학생님의 댓글

  • 익명
  • 작성일
Runtime: 58 ms, faster than 41.86% of Python3 online submissions for Minimum Genetic Mutation.
Memory Usage: 13.9 MB, less than 37.43% of Python3 online submissions for Minimum Genetic Mutation.
class Solution:
    def minMutation(self, start: str, end: str, bank: List[str]) -> int:
        # path
        bank = set(bank)

        def onediff(a,b):
            return sum(c1!=c2 for c1,c2 in zip(a,b)) == 1
        
        
        res = float('inf')
        
        def dfs(curr,depth):
            nonlocal res
            if depth > res: return
            
            if curr == end:
                res = min(res, depth)
                return
            
            bank.remove(curr)
            
            for string in bank:
                if onediff(curr,string):
                    dfs(string, depth+1)
            
            bank.add(curr)
            
        
        bank.add(start)
        dfs(start, 0)
        return -1 if res == float('inf') else res
전체 194 / 4 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 518 명
  • 오늘 방문자 4,985 명
  • 어제 방문자 7,414 명
  • 최대 방문자 14,831 명
  • 전체 회원수 1,544 명
알림 0