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