일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
Tags
- English
- 만화도
- realclass
- 프로젝트
- Writing
- 스탭퍼
- FIT XR
- 개발자
- 괜찮음
- 영어원서읽기
- 10분
- 30분
- 링피트
- 리얼 클래스
- 영어공부
- 뭐든
- 미드시청
- 3줄정리
- 월간
- 읽기
- Problem Solving
- 쓰릴오브파이트
- 사이드
- 화상영어
- 매일
- 잡생각
- 운동
- leetcode
- Daily Challenge
- 파비최
Archives
- Today
- Total
파비의 매일매일 공부기록
Today's Challenge 본문
https://leetcode.com/problems/word-ladder-ii/
dfs/bfs를 같이 써서 푸는 솔루션 참고. 매우 어려운 편 ㅠ
class Solution:
def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
if endWord not in wordList:
return []
wordList.append(beginWord)
wordList.append(endWord)
distance = {}
self.bfs(endWord, distance, wordList)
results = []
self.dfs(beginWord, endWord, distance, wordList, [beginWord], results)
return results
def bfs(self, start, distance, w):
distance[start] = 0
queue = deque([start])
while queue:
word = queue.popleft()
for next_word in self.get_next_words(word, w):
if next_word not in distance:
distance[next_word] = distance[word] + 1
queue.append(next_word)
def get_next_words(self, word, w):
words = []
for i in range(len(word)):
for c in 'abcdefghijklmnopqrstuvwxyz':
next_word = word[:i] + c + word[i+1:]
if next_word != word and next_word in w:
words.append(next_word)
return words
def dfs(self, curt, target, distance, w, path, results):
if curt == target:
results.append(list(path))
return
for word in self.get_next_words(curt, w):
if distance[word] != distance[curt] - 1:
continue
path.append(word)
self.dfs(word, target, distance, w, path, results)
path.pop()
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
Today's Challenge (0) | 2022.08.16 |
---|---|
Today's Challenge (0) | 2022.08.15 |
Today's Challenge (0) | 2022.08.13 |
Today's Challenge (0) | 2022.08.12 |
Today's Challenge (0) | 2022.08.11 |
Comments