


from collections import deque
def solution(n, words):
circle = [words[0]]
evalq = words[0][-1]
words = deque(words[1:]) # 첫 단어는 이미 방문했으므로 deque에서 제외
for i in range(1, len(words) + 1): # deque의 길이만큼 반복
current_word = words.popleft()
if current_word in circle:
return [n, (i+1) // n] if (i+1) % n == 0 else [(i+1) % n, (i+1) // n + 1]
if current_word[0] != evalq:
return [n, (i+1) // n] if (i+1) % n == 0 else [(i+1) % n, (i+1) // n + 1]
circle.append(current_word)
evalq = current_word[-1]
return [0, 0]
python의 덱 모듈을 이용해서 코드를 구현하였다.
큐 자료구조로 끝말잇기 구조를 생각하는 것이 필요했다.
처음 문제를 보며 어떤 식으로 푸는 것이 좋을 지 계속 생각하는 것이 중요!
def solution(n, words):
for p in range(1, len(words)):
if words[p][0] != words[p-1][-1] or words[p] in words[:p]: return [(p%n)+1, (p//n)+1]
else:
return [0,0]
다른 풀이가 효율적인 코드냐? 라고 묻는다면 words[p] in words[:p]이기 때문에 시간 복잡도가 n^2이 되어버린다.
이것을 고려하는 문제까지는 아니지만, 만약 시간복잡도를 생각해야했다면 큐 자료구조로 접근하는 것이 좋을 것이라 생각한다.