
문제
DFS/BFS 문제 입니다. 문제 조건을 제대로 파악하지 못해 혼자 해결하지 못했던 문제입니다.
그러나, 문제의 맥락을 이해하면 그래도 금방 이해할 수 있었던 것 같습니다. 저의 경우 BFS를 활용하였습니다.
depth 변수를 활용하여, 한 번에 한 개의 알파벳만 바꿀 수 있는 문제 조건을 만족하는 경우 1 증가하도록 하였습니다.
위 조건을 만족하는 경우와 더불어 방문되지 않은 경우를 만족하는 words를 계속 찾아나가줍니다.
탐색을 하며 찾은 현재 단어 (cur)가 target과 같으면, 그 떄의 depth를 리턴해주어 bfs가 종료되도록 합니다.
[Python]
from collections import deque
def bfs(begin, target, words,visited):
queue = deque()
queue.append((begin, 0))
while queue:
cur, depth = queue.popleft()
if cur == target:
return depth
#현재 단어, words의 단어를 하나씩 비교
for i in range(len(words)):
cnt = 0
if not visited[i]:
for j in range(len(cur)):
if cur[j] != words[i][j]:
cnt+=1
if cnt == 1:
queue.append((words[i],depth+1))
visited[i] = True
def solution(begin, target, words):
if target not in words:
return 0
visited = [False for _ in range(len(words))]
return bfs(begin, target, words,visited)'프로그래머스' 카테고리의 다른 글
| [프로그래머스] 2xn 타일링 - Python (0) | 2023.01.16 |
|---|---|
| [프로그래머스] 최솟값 만들기 - Python (0) | 2023.01.16 |
| [프로그래머스] 귤 고르기 - Python (0) | 2022.12.28 |
| [프로그래머스] 게임 맵 최단 거리 - Python (0) | 2022.12.13 |
| [프로그래머스] 더 맵게 - Java, Python (0) | 2022.12.07 |