Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Spring multimodule
- 프로그래머스
- infcon 2024
- spring batch 5.0
- 인프콘 2024
- 구글 OAuth login
- 디자인 패턴
- 커스텀 헤더
- JavaScript
- 항해99
- KPT회고
- @FeignClient
- 파이썬
- 취업리부트코스
- 빈 충돌
- 디자인패턴
- DesignPattern
- jwt
- 99클럽
- TiL
- 코딩테스트 준비
- 개발자부트캠프추천
- 전략패턴 #StrategyPattern #디자인패턴
- jwttoken
- 빈 조회 2개 이상
- Python
- 단기개발자코스
- 1주일회고
- 프로그래머스 이중우선순위큐
- 개발자 취업
Archives
- Today
- Total
m1ndy5's coding blog
LeetCode 207. Course Schedule with Python 본문
https://leetcode.com/problems/course-schedule/description/
풀지 못했던 문제ㅠㅠ
책 코드를 보고 풀었다!
import collections
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
# value가 list형태인 dictionary 선언
graph = collections.defaultdict(list)
for x, y in prerequisites:
graph[x].append(y)
# 추적하고 있는 코스
traced = set()
# 수강한 코스
visited = set()
def dfs(i):
# 이미 추적했다면 -> 순회 체크
if i in traced:
return False
# 이미 수강한 코스라면 True
if i in visited:
return True
# 추적리스트에 추가
traced.add(i)
# 선수과목들 체크
for y in graph[i]:
# 선수과목들의 선수과목들 재귀 -> traced에서 False가 리턴되면 최종결과도 False
if not dfs(y):
return False
# for문이 무사히 종료되면 traced에서 빼고 수강된 코스로 변경
traced.remove(i)
visited.add(i)
return True
# graph의 키값만 확인 -> 어짜피 선수과목 없는 코스는 무조건 들을 수 있음
for x in list(graph):
if not dfs(x):
return False
return True
내가 아직 재귀함수의 리턴값이 있을 경우의 코드를 잘 짜지 못하는 것 같다.
문제를 많이 풀어보면서 익혀야겠다!
'알고리즘 with python > 알고리즘 스터디' 카테고리의 다른 글
LeetCode 938. Range Sum of BST with Python (0) | 2024.01.12 |
---|---|
LeetCode 543. Diameter of Binary Tree with Python (0) | 2024.01.12 |
LeetCode 78. Subsets with Python (0) | 2024.01.11 |
LeetCode 51. N-Queens with Python 백트래킹 문제 (1) | 2024.01.10 |
LeetCode 77. Combinations(조합) with Python (0) | 2024.01.10 |