FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
coding-interview-patterns/java/Graphs/Prerequisites.java at main · ByteByteGoHq/coding-interview-patterns · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
ByteByteGoHq
/
coding-interview-patterns
Public
Notifications
You must be signed in to change notification settings
Fork
303
Star
1.3k
Code
Issues
0
Pull requests
5
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
coding-interview-patterns
/
java
/
Graphs
/
Prerequisites.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
47 lines (46 loc) · 1.64 KB
Breadcrumbs
coding-interview-patterns
/
java
/
Graphs
/
Prerequisites.java
Copy path
File metadata and controls
47 lines (46 loc) · 1.64 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import
java
.
util
.
ArrayList
;
import
java
.
util
.
HashMap
;
import
java
.
util
.
LinkedList
;
import
java
.
util
.
List
;
import
java
.
util
.
Map
;
import
java
.
util
.
Queue
;
public
class
Prerequisites
{
public
boolean
prerequisites
(
int
n
,
int
[][]
prerequisites
) {
Map
<
Integer
,
List
<
Integer
>>
graph
=
new
HashMap
<>();
int
[]
inDegrees
=
new
int
[
n
];
// Represent the graph as an adjacency list and record the in-
// degree of each course.
for
(
int
[]
edge
:
prerequisites
) {
int
prerequisite
=
edge
[
0
];
int
course
=
edge
[
1
];
graph
.
putIfAbsent
(
prerequisite
,
new
ArrayList
<>());
graph
.
get
(
prerequisite
).
add
(
course
);
inDegrees
[
course
]++;
}
Queue
<
Integer
>
queue
=
new
LinkedList
<>();
// Add all courses with an in-degree of 0 to the queue.
for
(
int
i
=
0
;
i
<
n
;
i
++) {
if
(
inDegrees
[
i
] ==
0
) {
queue
.
offer
(
i
);
}
}
int
enrolledCourses
=
0
;
// Perform topological sort.
while
(!
queue
.
isEmpty
()) {
int
node
=
queue
.
poll
();
enrolledCourses
++;
if
(
graph
.
containsKey
(
node
)) {
for
(
int
neighbor
:
graph
.
get
(
node
)) {
inDegrees
[
neighbor
]--;
// If the in-degree of a neighboring course becomes 0, add
// it to the queue.
if
(
inDegrees
[
neighbor
] ==
0
) {
queue
.
offer
(
neighbor
);
}
}
}
}
// Return true if we've successfully enrolled in all courses.
return
enrolledCourses
==
n
;
}
}
Back
|
FazBrowse Home
|
New Git URL