Stack 과 Dictionary를 이용해 풀이 하였습니다.
from collections import defaultdict
def check(word1, word2): # 1개의 알파벳만 다른 문자 확인
cnt = 0
for i in range(len(word1)):
if word1[i] != word2[i]:
cnt += 1
if cnt == 1:
return True
else:
return False
def solution(begin, target, words):
if target not in words:
return 0
graph = defaultdict(list)
for i in words:
if check(begin, i):
graph[begin].append(i)
for i in range(len(words)):
temp = []
for j in range(len(words)):
if i != j and check(words[i], words[j]):
temp.append(words[j])
graph[words[i]] = temp
stack = [begin]
cnt = 0
while stack:
if stack[-1] in graph:
if target in graph[stack[-1]]:
return cnt+1
stack.append(graph[stack.pop()].pop())
cnt += 1
'코딩문제' 카테고리의 다른 글
[LeetCode] 1578. Minimum Time to Make Rope Colorful (Python) (1) | 2022.10.04 |
---|---|
[LeetCode] 658. Find K Closest Elements (Python) (2) | 2022.09.29 |
[프로그래머스] [1차] 프렌즈4블록 (Python) (0) | 2022.06.09 |
프로그래머스 괄호 변환 (Python) (0) | 2022.06.02 |
[Leetcode] 237. Delete Node in a Linked List (0) | 2022.03.20 |