[파이썬] 프로그래머스 : 단어 변환 (Lv.2)
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이
0. 방향성 생각
시작단어를 words에 넣어놓고 이동 가능한 경로를 table 딕셔너리에 저장 후 거리 visit 딕셔너리도 만들기
무방향 그래프이므로 둘 다 추가해주기.
target 단어 유무로 완성 유무 판별. 탐색이 가능한 경우에만 탐색
전체코드
from itertools import combinations as C
from collections import deque
def solution(begin,target,words):
words = set(words)
words.add(begin)
table = {word : [] for word in words}
visit = {word : -1 for word in words}
if target not in words :
return 0
else:
temp = list(C(words,2))
for a,b in temp:
count = 0
for x,y in zip(a,b):
if x!=y : count +=1
if count == 1:
table[a].append(b)
table[b].append(a)
q = deque([begin])
visit[begin] = 0
while q:
x = q.popleft()
if x == target : break
if table[x]:
for nx in table[x]:
if visit[nx] == -1:
q.append(nx)
visit[nx] = visit[x]+1
if target in table:
return visit[target]
'Algorithm > Graph' 카테고리의 다른 글
[파이썬] 백준 9019 : DSLR (골드4) (0) | 2023.08.03 |
---|---|
[파이썬] 백준 17090 : 미로 탈출하기 (골드3) (0) | 2023.07.31 |
[파이썬] 백준 1525 : 퍼즐 (골드2) (0) | 2023.07.30 |
[파이썬] 백준 3184, 3187 : 양, 양치기 꿍 (실버1) (0) | 2023.07.13 |
[파이썬] 백준 연구소3 : 17142 (골드3) (0) | 2023.07.12 |
[파이썬] 백준 17141 : 연구소2 (골드4) (0) | 2023.07.12 |
[파이썬] 백준 14502 : 연구소 (골드4) (0) | 2023.07.11 |
댓글