begin | target | words | return |
---|---|---|---|
"hit" | "cog" | ["hot", "dot", "dog", "lot", "log", "cog"] | 4 |
"hit" | "cog" | ["hot", "dot", "dog", "lot", "log"] | 0 |
- 스택은 나중에 들어온 값을 pop하기 때문에 바로 이전의 단어와 다음 단어가 관련이 있음(알파벳 한개 차이)
- 그러나 큐(덱)은 처음 들어온 값을 pop하기 때문에
[dot, lot]에서 dot을 popleft하고 넣은 dog
즉 [lot, dog]에서 이후 lot에 대해 수행하기 때문에 각 단어에 대한 단계 즉 depth가 필요함.
def solution(begin, target, words):
if target not in words:
return 0
s = [begin]
visited = [0]*len(words)
ans = 0
while s:
value = s.pop()
if value == target:
return ans
for word in words:
if visited[words.index(word)] == 0:
cnt = 0
for a, b in zip(value, word):
if a != b:
cnt += 1
if cnt == 1:
s.append(word)
visited[words.index(word)] = 1
ans += 1
from collections import deque
def func(word, w):
cnt = 0
for a, b in zip(word, w):
if a != b:
cnt += 1
if cnt == 1:
return True
return False
def solution(begin, target, words):
if target not in words:
return 0
visited = []
q = deque()
q.append((begin, 0))
visited.append(begin)
ans = 0
while q:
w, d = q.popleft()
if w == target:
return d
for word in words:
if word not in visited and func(word, w):
q.append((word, d+1))
visited.append(word)
큐에 넣을 때 단어와 depth를 쌍으로 넣는다.
depth를 기록할 리스트를 따로 만들어도 됨.