-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0210_course_schedule_ii.html
More file actions
494 lines (421 loc) · 17.4 KB
/
Copy path0210_course_schedule_ii.html
File metadata and controls
494 lines (421 loc) · 17.4 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Course Schedule II - LeetCode 210</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#0210</span> Course Schedule II</h1>
<p><strong>Problem:</strong> Find an ordering of courses such that all prerequisites are satisfied. Return empty if impossible (cycle).</p>
<p><strong>Pattern:</strong> Topological Sort (Kahn's Algorithm) - BFS with in-degree tracking</p>
<div class="problem-meta">
<span class="meta-tag">🔗 Graph</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0210_course_schedule_ii/0210_course_schedule_ii.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Graph problems are like <strong>exploring a maze</strong>:</p>
<ul>
<li><strong>Nodes:</strong> Points or locations</li>
<li><strong>Edges:</strong> Connections between nodes</li>
<li><strong>Traverse:</strong> Use DFS or BFS to explore</li>
<li><strong>Track visited:</strong> Avoid infinite loops</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="visualization">
<svg id="mainSvg"></svg>
</div>
<div class="controls">
<button id="stepBtn">Step</button>
<button id="autoBtn">Auto Run</button>
<button id="resetBtn">Reset</button>
<div class="speed-control">
<label for="speed">Speed:</label>
<input type="range" id="speed" min="100" max="2000" value="800">
</div>
</div>
<div class="status" id="status">Click "Step" to find course ordering</div>
<div class="variables">
<div class="var-item">
<span class="var-label">Queue (0 in-degree):</span>
<span id="queueDisplay">[]</span>
</div>
<div class="var-item">
<span class="var-label">Result Order:</span>
<span id="resultDisplay">[]</span>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
from collections import defaultdict, deque
"""
LeetCode 210: Course Schedule II
Problem from LeetCode: https://leetcode.com/problems/course-schedule-ii/
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1.
You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must
take course bi first if you want to take course ai.
For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
Return the ordering of courses you should take to finish all courses. If there are many valid
answers, return any of them. If it is impossible to finish all courses, return an empty array.
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]]
Output: [0,1]
Explanation: There are a total of 2 courses to take. To take course 1 you should have finished
course 0. So the correct course order is [0,1].
Example 2:
Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [0,2,1,3]
Explanation: There are a total of 4 courses to take. To take course 3 you should have finished
both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].
Example 3:
Input: numCourses = 1, prerequisites = []
Output: [0]
Constraints:
- 1 <= numCourses <= 2000
- 0 <= prerequisites.length <= numCourses * (numCourses - 1)
- prerequisites[i].length == 2
- 0 <= ai, bi < numCourses
- ai != bi
- All the pairs [ai, bi] are distinct.
"""
class Solution:
def find_order(self, numCourses: int, prerequisites: List[List[int]]
) ->List[int]:
"""
Return the ordering of courses you should take to finish all courses.
Args:
numCourses: Number of courses (labeled from 0 to numCourses-1)
prerequisites: List of prerequisite pairs where [a, b] means course 'a' depends on course 'b'
Returns:
List[int]: The course order to take to finish all courses, or empty list if impossible
"""
WHITE = 1
GRAY = 2
BLACK = 3
is_possible = True
color = {}
adj_list = defaultdict(list)
topological_order = []
for i in range(numCourses):
color[i] = WHITE
for dest, src in prerequisites:
adj_list[src].append(dest)
def dfs(node):
nonlocal is_possible
if not is_possible:
return
color[node] = GRAY
for neighbor in adj_list[node]:
if color[neighbor] == WHITE:
dfs(neighbor)
elif color[neighbor] == GRAY:
is_possible = False
return
color[node] = BLACK
topological_order.append(node)
for i in range(numCourses):
if color[i] == WHITE:
dfs(i)
if not is_possible:
return []
return topological_order[::-1]
def find_order_b_f_s(self, numCourses: int, prerequisites: List[List[int]]
) ->List[int]:
"""
Alternative approach using BFS (Kahn's algorithm) for topological sorting.
Args:
numCourses: Number of courses
prerequisites: List of prerequisite pairs
Returns:
List[int]: The course order or empty list if impossible
"""
adj_list = defaultdict(list)
in_degree = [0] * numCourses
for dest, src in prerequisites:
adj_list[src].append(dest)
in_degree[dest] += 1
queue = deque([i for i in range(numCourses) if in_degree[i] == 0])
result = []
while queue:
course = queue.popleft()
result.append(course)
for neighbor in adj_list[course]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
queue.append(neighbor)
return result if len(result) == numCourses else []
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
numCourses = 2
prerequisites = [[1, 0]]
result = solution.find_order(numCourses, prerequisites)
print(result) # Output: [0, 1]
# Example 2
numCourses = 4
prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]]
result = solution.find_order(numCourses, prerequisites)
print(result) # Output: [0, 1, 2, 3] or [0, 2, 1, 3]
# Example 3
numCourses = 1
prerequisites = []
result = solution.find_order(numCourses, prerequisites)
print(result) # Output: [0]
</pre>
</div>
</div>
</div>
<script>
// 4 courses, prerequisites: [[1,0],[2,0],[3,1],[3,2]]
// 0 → 1 → 3
// → 2 ↗
const numCourses = 4;
const prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]];
let graph = {};
let inDegree = [];
let nodeStates = {}; // course -> 'queue' | 'processing' | 'done'
let queue = [];
let result = [];
let autoRunning = false;
let autoTimer = null;
let initialized = false;
const width = 700;
const height = 380;
const svg = d3.select("#mainSvg")
.attr("width", width)
.attr("height", height);
const positions = [
{x: 150, y: 180}, // Course 0
{x: 350, y: 100}, // Course 1
{x: 350, y: 260}, // Course 2
{x: 550, y: 180} // Course 3
];
function initGraph() {
graph = {};
inDegree = new Array(numCourses).fill(0);
for (let i = 0; i < numCourses; i++) {
graph[i] = [];
}
for (const [course, prereq] of prerequisites) {
graph[prereq].push(course);
inDegree[course]++;
}
}
function draw() {
svg.selectAll("*").remove();
svg.append("text")
.attr("x", width / 2).attr("y", 25)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text("Topological Sort: Course Ordering");
// Draw edges
for (const [course, prereq] of prerequisites) {
const from = positions[prereq];
const to = positions[course];
// Arrow
const dx = to.x - from.x;
const dy = to.y - from.y;
const len = Math.sqrt(dx * dx + dy * dy);
const ux = dx / len;
const uy = dy / len;
const startX = from.x + ux * 30;
const startY = from.y + uy * 30;
const endX = to.x - ux * 35;
const endY = to.y - uy * 35;
svg.append("line")
.attr("x1", startX).attr("y1", startY)
.attr("x2", endX).attr("y2", endY)
.attr("stroke", "#999")
.attr("stroke-width", 2)
.attr("marker-end", "url(#arrowhead)");
}
// Arrow marker
svg.append("defs").append("marker")
.attr("id", "arrowhead")
.attr("viewBox", "0 -5 10 10")
.attr("refX", 8)
.attr("refY", 0)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("path")
.attr("d", "M0,-5L10,0L0,5")
.attr("fill", "#999");
// Draw nodes
for (let i = 0; i < numCourses; i++) {
const pos = positions[i];
const state = nodeStates[i];
const deg = initialized ? inDegree[i] : 0;
let fill = "#e3f2fd", stroke = "#1976d2";
if (state === 'queue') {
fill = "#fff3e0"; stroke = "#ff9800";
} else if (state === 'processing') {
fill = "#ffeb3b"; stroke = "#f57c00";
} else if (state === 'done') {
fill = "#c8e6c9"; stroke = "#4caf50";
}
svg.append("circle")
.attr("cx", pos.x).attr("cy", pos.y).attr("r", 30)
.attr("fill", fill).attr("stroke", stroke).attr("stroke-width", 2);
svg.append("text")
.attr("x", pos.x).attr("y", pos.y + 6)
.attr("text-anchor", "middle")
.attr("font-size", "20px")
.attr("font-weight", "bold")
.text(i);
// In-degree label
if (initialized) {
svg.append("circle")
.attr("cx", pos.x + 25).attr("cy", pos.y - 25)
.attr("r", 14)
.attr("fill", deg === 0 ? "#a5d6a7" : "#ffcc80")
.attr("stroke", deg === 0 ? "#4caf50" : "#ff9800");
svg.append("text")
.attr("x", pos.x + 25).attr("y", pos.y - 21)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold")
.text(deg);
}
}
// Result visualization
svg.append("text")
.attr("x", 50).attr("y", height - 55)
.attr("font-weight", "bold")
.text("Course Order:");
result.forEach((course, i) => {
svg.append("rect")
.attr("x", 150 + i * 50).attr("y", height - 70)
.attr("width", 40).attr("height", 35)
.attr("rx", 5)
.attr("fill", "#c8e6c9").attr("stroke", "#4caf50");
svg.append("text")
.attr("x", 170 + i * 50).attr("y", height - 47)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.text(course);
if (i < result.length - 1) {
svg.append("text")
.attr("x", 200 + i * 50).attr("y", height - 47)
.attr("text-anchor", "middle")
.attr("font-size", "16px")
.text("→");
}
});
// Legend
svg.append("text")
.attr("x", 10).attr("y", height - 15)
.attr("font-size", "11px")
.text("Circle number = in-degree (prerequisites remaining)");
}
function step() {
if (!initialized) {
initGraph();
initialized = true;
// Add nodes with 0 in-degree to queue
for (let i = 0; i < numCourses; i++) {
if (inDegree[i] === 0) {
queue.push(i);
nodeStates[i] = 'queue';
}
}
document.getElementById("queueDisplay").textContent =
`[${queue.join(', ')}]`;
document.getElementById("status").textContent =
`Initialized. Courses with no prerequisites: [${queue.join(', ')}]`;
draw();
return true;
}
if (queue.length === 0) {
if (result.length === numCourses) {
document.getElementById("status").textContent =
`Done! Valid ordering: [${result.join(' → ')}]`;
} else {
document.getElementById("status").textContent =
`Cycle detected! Cannot complete all courses.`;
}
draw();
return false;
}
const course = queue.shift();
nodeStates[course] = 'processing';
document.getElementById("status").textContent =
`Processing course ${course}...`;
// Add to result
result.push(course);
document.getElementById("resultDisplay").textContent =
`[${result.join(', ')}]`;
// Reduce in-degree of neighbors
for (const next of graph[course]) {
inDegree[next]--;
if (inDegree[next] === 0) {
queue.push(next);
nodeStates[next] = 'queue';
}
}
nodeStates[course] = 'done';
document.getElementById("queueDisplay").textContent =
`[${queue.join(', ')}]`;
document.getElementById("status").textContent =
`Completed course ${course}. Updated neighbor in-degrees.`;
draw();
return queue.length > 0 || result.length < numCourses;
}
function reset() {
graph = {};
inDegree = [];
nodeStates = {};
queue = [];
result = [];
initialized = false;
autoRunning = false;
if (autoTimer) clearInterval(autoTimer);
document.getElementById("queueDisplay").textContent = "[]";
document.getElementById("resultDisplay").textContent = "[]";
document.getElementById("status").textContent =
'Click "Step" to find course ordering';
document.getElementById("autoBtn").textContent = "Auto Run";
draw();
}
function autoRun() {
if (autoRunning) {
autoRunning = false;
clearInterval(autoTimer);
document.getElementById("autoBtn").textContent = "Auto Run";
} else {
autoRunning = true;
document.getElementById("autoBtn").textContent = "Pause";
const speed = 2100 - document.getElementById("speed").value;
autoTimer = setInterval(() => {
if (!step()) {
autoRunning = false;
clearInterval(autoTimer);
document.getElementById("autoBtn").textContent = "Auto Run";
}
}, speed);
}
}
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("autoBtn").addEventListener("click", autoRun);
document.getElementById("resetBtn").addEventListener("click", reset);
draw();
</script>
</body>
</html>