728x90
https://school.programmers.co.kr/learn/courses/30/lessons/43163
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
이 문제가 BFS를 이용하는 이유: "최소 단계 변환을 찾는 문제 -> 최단 경로 문제 -> BFS를 이용"
from collections import deque
def solution(begin, target, words):
if target not in words:
return 0
q = deque()
q.append([begin, 0])
visited = [0]*len(words)
def is_one_letter_diff(word1, word2):
count = 0
for a, b in zip(word1, word2):
if a != b:
count += 1
if count > 1:
return False
return True if count == 1 else False
def bfs():
while q:
word, steps = q.popleft()
if word == target:
return steps
for i in range(len(words)):
if not visited[i] and is_one_letter_diff(word, words[i]):
visited[i] = 1
q.append((words[i], steps+1))
return 0
return bfs()
백준: 단지 번호 붙이기,
728x90
'[Coding Test] > [프로그래머스]' 카테고리의 다른 글
[프로그래머스] lv1 K번째수 / 파이썬, 고득점kit (0) | 2023.10.03 |
---|---|
[프로그래머스] lv3 아이템 줍기 / 파이썬 [해설과 다른 풀이], 고득점kit (0) | 2023.09.08 |
[프로그래머스] 게임 맵 최단거리 (2) | 2023.09.07 |
[프로그래머스] 네트워크 (0) | 2023.09.03 |
[프로그래머스] 타겟넘버 (0) | 2023.09.03 |