Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions course-schedule/freemjstudio.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

course-schedule/freemjstudio.py
class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:

        # cycle 을 감지하면 false 를 리턴한다.
        graph = [[] for _ in range(numCourses)]

        # a <- b
        for a, b in prerequisites:
            graph[b].append(a)

        state = [0] * numCourses
        # 0: unvisited 1: visiting 2: done

        def dfs(node):
            if state[node] == 1:
                return False

            if state[node] == 2:
                return True

            state[node] = 1 # visiting

            for next_node in graph[node]:
                if dfs(next_node) == False:
                    return False

            state[node] = 2 # done
            return True

        for course in range(numCourses):
            if dfs(course) == False:
                return False

        return True
  • 패턴: Depth-First Search, Graph
  • 설명: 그래프를 구성하고 DFS로 사이클 여부를 탐지하는 패턴으로, 방문 상태를 추적해 순환 여부를 판단한다. 사이클이 있으면 false, 없으면 true를 반환한다.

📊 시간/공간 복잡도 분석

복잡도
Time O(N + P)
Space O(N + P)

피드백: 그래프를 인접 리스트로 구성하고 각 노드를 DFS하며 사이클 여부를 검사한다. 상태 배열로 방문 중인 노드를 추적해 사이클을 탐지한다.

개선 제안: 현재 구현이 적절해 보입니다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:

# cycle 을 감지하면 false 를 리턴한다.
graph = [[] for _ in range(numCourses)]

# a <- b
for a, b in prerequisites:
graph[b].append(a)

state = [0] * numCourses
# 0: unvisited 1: visiting 2: done

def dfs(node):
if state[node] == 1:
return False

if state[node] == 2:
return True

state[node] = 1 # visiting

for next_node in graph[node]:
if dfs(next_node) == False:
return False

state[node] = 2 # done
return True

for course in range(numCourses):
if dfs(course) == False:
return False

return True
Loading