150強訪談簡單

課程安排

「課程表」問題的詳細指南和 Python 實作。

問題陳述

簡單

您必須選修 numCourses 課程,標記為從 0 到 numCourses - 1。您將獲得一個陣列先決條件,其中先決條件 [i] = [ai, bi] 表示如果您想選修課程 ai,則必須先選修課程 bi。

例如,[0, 1] 對錶示要學習課程 0,您必須先學習課程 1。

如果您可以完成所有課程,則返回 True。否則,返回 False。

寫一個函數 canFinish(numCourses: int, prerequisites: List[List[int]]) -> bool

約束條件
  • 1 <= numCourses <= 2000
  • 0 <= len(prerequisites) <= 5000
  • prerequisites[i].length == 2
  • 0 <= ai, bi < numCourses

範例

Example 1
Input
numCourses = 2, prerequisites = [[1,0]]
Output
True
Explanation

To take course 1 you should have finished course 0. So it is possible.

Example 2
Input
numCourses = 2, prerequisites = [[1,0],[0,1]]
Output
False
Explanation

To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. This is a cycle and therefore impossible.

Need a Hint?
考慮使用特定於圖的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。