https://school.programmers.co.kr/learn/courses/30/lessons/43163
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
visited가 set인 경우
def solution(begin, target, words):
if target not in words:
return 0 # target이 words에 없으면 변환 불가
# 단어 간 1글자 차이를 확인하는 함수
def is_one_char_diff(word1, word2):
diff_count = 0
for a, b in zip(word1, word2):
if a != b:
diff_count += 1
if diff_count > 1:
return False
return diff_count == 1
# BFS 탐색
from collections import deque
queue = deque([(begin, 0)]) # 시작 단어와 변환 단계 저장
visited = set() # 방문한 단어 기록
while queue:
current_word, steps = queue.popleft()
# 목표 단어에 도달하면 단계 반환
if current_word == target:
return steps
# 방문하지 않은 단어 중 1글자 차이인 단어 탐색
for word in words:
if word not in visited and is_one_char_diff(current_word, word):
visited.add(word)
queue.append((word, steps + 1))
# 목표 단어에 도달할 수 없는 경우
return 0
visited가 리스트인 경우
def solution(begin, target, words):
if target not in words:
return 0 # target이 words에 없으면 변환 불가
# 단어 간 1글자 차이를 확인하는 함수
def is_one_char_diff(word1, word2):
diff_count = 0
for a, b in zip(word1, word2):
if a != b:
diff_count += 1
if diff_count > 1:
return False
return diff_count == 1
# BFS 탐색
from collections import deque
queue = deque([(begin, 0)]) # 시작 단어와 변환 단계 저장
visited = [False] * len(words) # 방문 여부를 리스트로 관리
while queue:
current_word, steps = queue.popleft()
# 목표 단어에 도달하면 단계 반환
if current_word == target:
return steps
# 방문하지 않은 단어 중 1글자 차이인 단어 탐색
for i, word in enumerate(words):
if not visited[i] and is_one_char_diff(current_word, word):
visited[i] = True
queue.append((word, steps + 1))
# 목표 단어에 도달할 수 없는 경우
return 0
- 특정 조건을 만족하는지 확인하는 함수를 따로 빼는 것을 연습하자....
- 문제를 잘 이해하자...나는 위치도 고정해야되는지 모르고 그냥 겹치는 알파벳이 몇개인지만 확인하려고 했다ㅠㅠ
- queue.append해주는거 잊지 말자...
- zip을 잘 활용해보자! 두 문자열을 하나씩 풀어서 비교
https://www.daleseo.com/python-zip/
파이썬의 zip() 내장 함수로 데이터 엮기
Engineering Blog by Dale Seo
www.daleseo.com
'프로그래머스' 카테고리의 다른 글
[Python/파이썬]프로그래머스 86491. 최소직사각형 (0) | 2025.01.18 |
---|---|
프로그래머스 87946. 피로도 (0) | 2025.01.18 |
프로그래머스 1844. 게임 맵 최단거리 (0) | 2025.01.17 |
프로그래머스 43165. 타겟 넘버 (0) | 2025.01.15 |
프로그래머스 84512. 모음사전 (0) | 2025.01.15 |