문제
https://programmers.co.kr/learn/courses/30/lessons/43163
코딩테스트 연습 - 단어 변환
두 개의 단어 begin, target과 단어의 집합 words가 있습니다. 아래와 같은 규칙을 이용하여 begin에서 target으로 변환하는 가장 짧은 변환 과정을 찾으려고 합니다. 1. 한 번에 한 개의 알파벳만 바꿀 수
programmers.co.kr
코드
1) BFS 이용
from collections import deque
def solution(begin, target, words):
answer = 0
if target not in words:
return 0
visited = [0] * len(words)
queue = deque([begin])
while queue:
node = queue.popleft()
if node == target:
return answer
for i in range(len(words)):
if not visited[i] and node != words[i]:
count = 0
for j in range(len(begin)):
if node[j] != words[i][j]:
count += 1
if count == 1:
queue.append(words[i])
visited[i] = visited[i] + 1
answer += 1
return answer
정답이긴한데.. 테스트 케이스에서는 하나의 실패 케이스가 존재한다.
=> 아래 풀이는 둘 다 성공
2) BFS 이용
from collections import deque
def solution(begin, target, words):
answer = 0
if target not in words:
return 0
visited = [0] * len(words)
queue = deque([[begin, 0]])
while queue:
word, count = queue.popleft()
if word == target:
answer = count
break
for i in range(len(words)):
temp = 0
if not visited[i]:
for j in range(len(word)):
if word[j] != words[i][j]:
temp += 1
if temp == 1:
queue.append([words[i], count+1])
visited[i] = 1
return answer
queue에 count변수를 함꼐 저장하는 방식으로 풀 수 있구나!!!!@!!!!
'⏳ 알고리즘 > python 알고리즘 문제 풀이' 카테고리의 다른 글
리트코드 - 53. Maximum Subarray (0) | 2022.04.28 |
---|---|
리트코드 - 509. Fibonacci Number (0) | 2022.04.27 |
프로그래머스 - LV3. 네트워크 (0) | 2022.03.25 |
프로그래머스 - [3차] 방금그곡 (2018 KAKAO BLIND RECRUITMENT) (0) | 2021.11.19 |
프로그래머스 - 삼각 달팽이(월간 코드 챌린지 시즌1) (0) | 2021.11.19 |