Skip to content

Commit 49fea28

Browse files
authored
Update Solution2.java
1 parent 2ad5648 commit 49fea28

File tree

1 file changed

+27
-34
lines changed

1 file changed

+27
-34
lines changed
Lines changed: 27 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,32 @@
11
class Solution {
2-
private char[][] grid;
3-
private int m;
4-
private int n;
2+
public int[] findOrder(int numCourses, int[][] prerequisites) {
3+
List<Integer>[] graph = new List[numCourses];
4+
int[] inDegrees = new int[numCourses];
55

6-
public int numIslands(char[][] grid) {
7-
m = grid.length;
8-
n = grid[0].length;
9-
this.grid = grid;
10-
int ans = 0;
11-
for (int i = 0; i < m; ++i) {
12-
for (int j = 0; j < n; ++j) {
13-
if (grid[i][j] == '1') {
14-
bfs(i, j);
15-
++ans;
16-
}
17-
}
18-
}
19-
return ans;
6+
for (int i = 0; i < numCourses; ++i)
7+
graph[i] = new ArrayList<>();
8+
9+
for (int[] prerequisite : prerequisites) {
10+
graph[prerequisite[1]].add(prerequisite[0]);
11+
++inDegrees[prerequisite[0]];
2012
}
2113

22-
private void bfs(int i, int j) {
23-
grid[i][j] = '0';
24-
Deque<int[]> q = new ArrayDeque<>();
25-
q.offer(new int[] {i, j});
26-
int[] dirs = {-1, 0, 1, 0, -1};
27-
while (!q.isEmpty()) {
28-
int[] p = q.poll();
29-
for (int k = 0; k < 4; ++k) {
30-
int x = p[0] + dirs[k];
31-
int y = p[1] + dirs[k + 1];
32-
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1') {
33-
q.offer(new int[] {x, y});
34-
grid[x][y] = '0';
35-
}
36-
}
37-
}
14+
int[] ans = new int[numCourses];
15+
int index = 0;
16+
17+
Queue<Integer> q = new LinkedList<>();
18+
for (int i = 0; i < numCourses; ++i)
19+
if (inDegrees[i] == 0)
20+
q.offer(i);
21+
22+
while (!q.isEmpty()) {
23+
int u = q.poll();
24+
ans[index++] = u;
25+
for (int v : graph[u])
26+
if (--inDegrees[v] == 0)
27+
q.offer(v);
3828
}
39-
}
29+
30+
return index == numCourses ? ans : new int[] {};
31+
}
32+
}

0 commit comments

Comments
 (0)