# C++ DFS solution and BFS solution

• DFS solution:

`#define WHITE 0`
`#define GRAY 1`
`#define BLACK 2`

``````class Gragh {
public:
friend class Solution;
Gragh(int nums) : Vnums(nums), cycle(false) {
visited = vector<int>(nums, WHITE);
}
private:
int Vnums;
bool cycle;
vector<int> visited;

void addEdge(int u, int v) {
}
vector<int> schedule() {
vector<int> result;
for (int i = 0; i < Vnums; i++) {
if (cycle) return vector<int>();
if (!cycle && visited[i] == WHITE) dfs(i, result);
}
if (result.size() != Vnums) return vector<int>();
else return result;
}
void dfs(int node, vector<int> &result) {
visited[node] = GRAY;
for (int i = 0; i < adj[node].size(); i++) {
if (visited[adj[node][i]] == GRAY) { cycle = true; return;}
}
result.insert(result.begin(), node);
visited[node] = BLACK;
}
};
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prer) {
Gragh myGragh(numCourses);
for (auto item : prer)
return myGragh.schedule();
}
``````

BFS solution:

`````` class Gragh {
public:
int Vnums;
vector<int> indegree;
Gragh(int nums) : Vnums(nums) {
indegree = vector<int>(nums, 0);
}
void addEdge(int u, int v) {
}
vector<int> schedule() {
vector<int> result;
queue<int> myQ;
for (int i = 0; i < Vnums; i++) {
if (indegree[i] == 0) myQ.push(i);
}
while (!myQ.empty()){
result.push_back(myQ.front());
myQ.pop();
for (auto item : adj[result.back()]) {
--indegree[item];
if (indegree[item] == 0) myQ.push(item);
}
}
if (result.size() != Vnums) return vector<int>();
else return result;
}
};
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prer) {
Gragh myGragh(numCourses);
for (auto item : prer) {