Topological Sort_Course Schedudle
There are a total of numCourses
courses you have to take, labeled from 0
to numCourses-1
.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
Example 1: Input : numCourses = 2, prerequisites = [[1,0]] Output : true Explanation : There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
Example 2: Input : numCourses = 2, prerequisites = [[1,0],[0,1]] Output : false Explanation : There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
Example 3: Input : [[1,0],[2,1],[3,2]] Output : true
์๋ฃ๊ตฌ์กฐ : 1์ฐจ์ ๋ฐฐ์ด, ํ
์๊ณ ๋ฆฌ์ฆ 1. ๊ณผ๋ชฉ ์๋งํผ ํฌ๊ธฐ์ 1์ฐจ์ ๋ฐฐ์ด(inDegree)์ ์์ฑํ์ฌ ์ด๊ธฐ ๊ฐ์ 0์ผ๋ก ์ ํ ํ๋ค. 2. '0'์ธ ๊ฒ(๋ง์ง๋ง ๊ณผ๋ชฉ)์ ํ์ ๋ฃ๋๋ค. 3. ํ์ 1์ฐจ์ ๋ฐฐ์ด์ ์๋ค๊ฐ๋ค ํ๋ฉฐ ์์ ์ ์ด์ ๊ณผ์ ์ด acyclic์ธ์ง backtrackingํ๋ค. 0->1->2->3 ์ผ ๋, 0->1 : 1๊ฐ, 1->2 : 1๊ฐ, 2->3 : 1๊ฐ ์ฌ์ผํ๋ค. ๋ง์ง๋ง ๊ณผ๋ชฉ(3)์์ ๋ฐฑํธ๋ํนํ์ฌ ์์ ์ฝ์ค ์๋ฅผ ๊ฐ์ฐํ์ฌ 0์ผ๋ก ๋ง๋ ๋ค.
ํ์์ ๋ ธ๋(=์ฝ์ค๋ฅผ ์๋ฏธ)๋ฅผ ๊บผ๋ด์จ๋ค. (course) 2์ฐจ์ ๋ฐฐ์ด(nums)์์ course(nums[ i ][0]๋ฅผ ์ฐพ๊ณ , course ์ ์ด์๊ณผ์ (nums[ i ][1])์ inDegree์์ ๊ฐ์ฐํ๋ค. inDegree์์ ๊ฐ์ฐํ nums[ i ][1](=์ฝ์ค)์ด 0์ด๋ฉด, 0์ด ๋ ์ฝ์ค๋ฅผ ํ์ ๋ค์ ๋ฃ๋๋ค. 4. 1์ฐจ์ ๋ฐฐ์ด์ ๋ชจ๋ ์์๊ฐ 0์ด๋ฉด ์ฐธ์ด ๋๋ฉฐ true๋ฅผ ๋ฆฌํดํ๋ค.
Last updated