leetcode 207 Course Schedule

Leetcode Topological Sort

BFS

public:
	vector degree;
	map> graph;
	bool canFinish(int numCourses, vector>& prerequisites) {
		degree = vector(numCourses, 0);
		for (int i = 0; i < prerequisites.size(); i++) {
			graph[prerequisites[i][1]].push_back(prerequisites[i][0]);
			degree[prerequisites[i][0]] += 1;
		}
		int i = 0;
		int j = 0;
		bool flag = false;
		for (i = 0; i < numCourses; i++) {
			flag = false;
			for (j = 0; j < numCourses; j++) {
				if (degree[j] == 0) {
					degree[j] -= 1;
					flag = true;
					break;
				}
			}
			if (!flag) {
				return false;
			}
			for (int k = 0; k < graph[j].size(); k++) {
				degree[graph[j][k]] -= 1;
			}
		
		}
		return true;  // true --> the graph has not a cycle
	}

DFS

class Solution {
public:
	vector> graph;
	bool canFinish(int numCourses, vector>& prerequisites) {
		graph = vector>(numCourses);
		for (int i = 0; i < prerequisites.size(); i++) {
			graph[prerequisites[i][1]].push_back(prerequisites[i][0]);
		}
		vector v(numCourses, 0);
		for (int j = 0; j < graph.size(); j++) {
			if (dfs(j, v) == false) {
				return false; // false --> the graph has a cycle
			}
		}
		return true;  // true --> the graph has not a cycle
	}

private:
	bool dfs(int j, vector &v) {
		// visiting -->  1
		// visited  -->  2
		if (v[j] == 1) return false;
		if (v[j] == 2) return true;
		v[j] = 1;
		for (int i = 0; i < graph[j].size(); i++) {
			if (dfs(graph[j][i], v) == false) {
				return false;
			}
		}
		v[j] = 2;
		return true;
	}
};

你可能感兴趣的:(数据结构,leetcode,算法)