Skip to content

Update Solution2.java #3110

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 27 additions & 34 deletions solution/0200-0299/0200.Number of Islands/Solution2.java
Original file line number Diff line number Diff line change
@@ -1,39 +1,32 @@
class Solution {
private char[][] grid;
private int m;
private int n;
public int[] findOrder(int numCourses, int[][] prerequisites) {
List<Integer>[] graph = new List[numCourses];
int[] inDegrees = new int[numCourses];

public int numIslands(char[][] grid) {
m = grid.length;
n = grid[0].length;
this.grid = grid;
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == '1') {
bfs(i, j);
++ans;
}
}
}
return ans;
for (int i = 0; i < numCourses; ++i)
graph[i] = new ArrayList<>();

for (int[] prerequisite : prerequisites) {
graph[prerequisite[1]].add(prerequisite[0]);
++inDegrees[prerequisite[0]];
}

private void bfs(int i, int j) {
grid[i][j] = '0';
Deque<int[]> q = new ArrayDeque<>();
q.offer(new int[] {i, j});
int[] dirs = {-1, 0, 1, 0, -1};
while (!q.isEmpty()) {
int[] p = q.poll();
for (int k = 0; k < 4; ++k) {
int x = p[0] + dirs[k];
int y = p[1] + dirs[k + 1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1') {
q.offer(new int[] {x, y});
grid[x][y] = '0';
}
}
}
int[] ans = new int[numCourses];
int index = 0;

Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < numCourses; ++i)
if (inDegrees[i] == 0)
q.offer(i);

while (!q.isEmpty()) {
int u = q.poll();
ans[index++] = u;
for (int v : graph[u])
if (--inDegrees[v] == 0)
q.offer(v);
}
}

return index == numCourses ? ans : new int[] {};
}
}
Loading