← Home

1462. Course Schedule IV

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
graph traversalC++Markdown
146

Let's make this one less mysterious. For 1462. Course Schedule IV, the solution in this repository is mainly a graph traversal solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: graph traversal.

The notes already sitting in the source point us in the right direction:

  • WA
  • 67 / 68 test cases passed.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are checkIfPrerequisite, visited.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • A set is doing the membership or uniqueness work, which keeps the main loop readable.
  • The queue gives the solution a level-by-level or frontier-style traversal.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N^3), space: O(N^2)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//WA
02//67 / 68 test cases passed.
03/*
045
05[[3,4],[2,3],[1,2],[0,1]]
06[[0,4],[4,0],[1,3],[3,0]]
07*/
08
09class Solution {
10public:
11    vector<bool> checkIfPrerequisite(int n, vector<vector<int>>& prerequisites, vector<vector<int>>& queries) {
12        //bfs
13        map<int, set<int>> graph;
14        
15        //this only extends existing edges, so it gives WA!
16        for(vector<int>& pre : prerequisites){
17            graph[pre[0]].insert(pre[1]);
18            for(auto it = graph.begin(); it != graph.end(); it++){
19                if(it->second.find(pre[0]) != it->second.end()){
20                    it->second.insert(pre[1]);
21                }
22            }
23        }
24        
25        vector<bool> ans(queries.size(), false);
26        
27        for(int i = 0; i < queries.size(); i++){
28            if(graph.find(queries[i][0]) == graph.end()){
29                ans[i] = false;
30            }else{
31                ans[i] = (graph[queries[i][0]].find(queries[i][1]) != graph[queries[i][0]].end());
32            }
33        }
34        
35        return ans;
36    }
37};
38
39//Floyd–Warshall(All Pairs Shortest Path)
40//https://leetcode.com/problems/course-schedule-iv/discuss/660509/JavaPython-FloydWarshall-Algorithm-Clean-code-O(n3)
41//Runtime: 1220 ms, faster than 20.27% of C++ online submissions for Course Schedule IV.
42//Memory Usage: 62.1 MB, less than 100.00% of C++ online submissions for Course Schedule IV.
43//time: O(N^3), space: O(N^2)
44class Solution {
45public:
46    vector<bool> checkIfPrerequisite(int n, vector<vector<int>>& prerequisites, vector<vector<int>>& queries) {
47        vector<vector<bool>> connected(n, vector<bool>(n, false));
48        
49        for(auto pre : prerequisites){
50            connected[pre[0]][pre[1]] = true;
51        }
52        
53        for(int i = 0; i < n; i++){
54            connected[i][i] = true;
55        }
56        
57        //each time add a middle point
58        for(int k = 0; k < n; k++){
59            //check if the middle point make each pair of (i, j) connected
60            for(int i = 0; i < n; i++){
61                for(int j = 0; j < n; j++){
62                    connected[i][j] = connected[i][j] || 
63                        (connected[i][k] && connected[k][j]);
64                }
65            }
66        }
67        
68        vector<bool> ans(queries.size());
69        
70        for(int i = 0; i < queries.size(); i++){
71            ans[i] = connected[queries[i][0]][queries[i][1]];
72        }
73        
74        return ans;
75    }
76};
77
78//BFS
79//https://leetcode.com/problems/course-schedule-iv/discuss/662276/C%2B%2B-or-100-Faster-and-Memory-Optimized
80//Runtime: 376 ms, faster than 92.70% of C++ online submissions for Course Schedule IV.
81//Memory Usage: 66.2 MB, less than 100.00% of C++ online submissions for Course Schedule IV.
82//time: O(N^2), space: O(N^2)
83class Solution {
84public:
85    vector<bool> checkIfPrerequisite(int n, vector<vector<int>>& prerequisites, vector<vector<int>>& queries) {
86        vector<vector<bool>> connected(n, vector<bool>(n, false));
87        vector<vector<int>> graph(n);
88        
89        for(auto pre : prerequisites){
90            connected[pre[0]][pre[1]] = true;
91            graph[pre[0]].push_back(pre[1]);
92        }
93        
94        for(int i = 0; i < n; i++){
95            connected[i][i] = true;
96        }
97        
98        /*
99        each time choose a starting point
100        and see which nodes it can visit by bfs
101        */
102        for(int start = 0; start < n; start++){
103            queue<int> q;
104            vector<bool> visited(n, false);
105            q.push(start);
106            visited[start] = true;
107            while(!q.empty()){
108                int cur = q.front(); q.pop();
109                
110                for(int nei : graph[cur]){
111                    if(!visited[nei]){
112                        //start can connect to nei through bfs
113                        connected[start][nei] = true;
114                        visited[nei] = true;
115                        q.push(nei);
116                    }
117                }
118            }
119        }
120        
121        vector<bool> ans(queries.size());
122        
123        for(int i = 0; i < queries.size(); i++){
124            ans[i] = connected[queries[i][0]][queries[i][1]];
125        }
126        
127        return ans;
128    }
129};

Cost

Complexity

Time
O(N^3), space: O(N^2)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.