File tree Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ 풀이 :
3+ BFS를 이용한 진입차수 기반 위상정렬
4+
5+ prerequisite에서 course로 방향 간선이 생기는 그래프 문제
6+ 그래프는 이중벡터로 만들고 선수과목 관계에 따라 초기화 (graph[선수과목]에 상위과목들을 담는다)
7+ 과목을 들으려면 필요한 선수과목 수 -> inDgree에 배열로 저장
8+
9+ 선수과목이 필요없는 (inDgree에서 성분이 0인) 과목 먼저 큐에 넣는다
10+ 과목을 수강하면 finished++로 수강완료 표시, 해당 과목을 선수과목으로 가지는 과목들에서 진입차수를 1씩 뺸다
11+ 진입차수가 0이 되는 과목을 큐에 넣어서 반복
12+
13+ 큐가 완전히 빌 떄까지 반복했을 떄 모든 과목을 이수 가능하면(finished == numCourses) true 아니면 false
14+
15+ 수강과목 수 : V(Vertex), 선수과목 관계 수 : E(Edge)
16+
17+ TC : O (V + E)
18+ prerequisites(E)과 numCourses(V)만큼에 대해 각각 반복문
19+
20+ SC : O (V + E)
21+ 기본적으로 V만큼의 빈 벡터를 가지고 있고 추가적으로 E만큼 성분이 push된다
22+ */
23+
24+ #include < vector>
25+ #include < queue>
26+
27+ using namespace std ;
28+
29+ class Solution {
30+ public:
31+ bool canFinish (int numCourses, vector<vector<int >>& prerequisites) {
32+ vector<vector<int >> graph (numCourses);
33+ vector<int > inDgree (numCourses, 0 );
34+
35+ for (auto & prerequisite : prerequisites) {
36+ int crs = prerequisite[0 ];
37+ int pre = prerequisite[1 ];
38+ graph[pre ].push_back (crs);
39+ inDgree[crs]++;
40+ }
41+
42+ queue<int > q;
43+ int finished = 0 ;
44+
45+ for (int i = 0 ; i < numCourses; i++) {
46+ if (inDgree[i] == 0 )
47+ q.push (i);
48+ }
49+
50+ while (!q.empty ()) {
51+ int cur = q.front ();
52+ q.pop ();
53+
54+ for (auto & next : graph[cur]) {
55+ if (--inDgree[next] == 0 )
56+ q.push (next);
57+ }
58+ finished++;
59+ }
60+
61+ return finished == numCourses;
62+ }
63+ };
You can’t perform that action at this time.
0 commit comments