Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static Integer count_islands(ArrayList<ArrayList<Integer>> matrix) {
- int nr = matrix.size();
- int nc = matrix.get(0).size();
- boolean[][] visited = new boolean[nr][nc];
- int number_of_islands = 0;
- for (int i = 0; i < nr; i++) {
- for (int j = 0; j < nc; j++) {
- if (!visited[i][j] && matrix.get(i).get(j) == 1) {
- bfs(i, j, matrix, visited);
- number_of_islands += 1;
- }
- }
- }
- return number_of_islands;
- }
- static void bfs(int i, int j, ArrayList<ArrayList<Integer>> matrix, boolean[][] visited) {
- visited[i][j] = true;
- Queue<int[]> q = new LinkedList<int[]>();
- q.offer(new int[]{i,j});
- while (!q.isEmpty()) {
- int[] curr = q.poll();
- int curr_i = curr[0];
- int curr_j = curr[1];
- for (int[] neighbor : getNeighbors(curr_i, curr_j, matrix)) {
- int n_i = neighbor[0];
- int n_j = neighbor[1];
- if (!visited[n_i][n_j]) {
- q.offer(new int[]{n_i, n_j});
- visited[n_i][n_j] = true;
- }
- }
- }
- }
- static ArrayList<int[]> getNeighbors(int i, int j, ArrayList<ArrayList<Integer>> matrix) {
- int nr = matrix.size();
- int nc = matrix.get(0).size();
- ArrayList<int[]> neighbors = new ArrayList<int[]>();
- if (i - 1 >= 0 && i - 1 <= nr - 1 && matrix.get(i - 1).get(j) == 1) {
- neighbors.add(new int[]{i - 1, j});
- }
- if (i + 1 >= 0 && i + 1 <= nr - 1 && matrix.get(i + 1).get(j) == 1) {
- neighbors.add(new int[]{i + 1, j});
- }
- if (j - 1 >= 0 && j - 1 <= nc - 1 && matrix.get(i).get(j - 1) == 1) {
- neighbors.add(new int[]{i, j - 1});
- }
- if (j + 1 >= 0 && j + 1 <= nc - 1 && matrix.get(i).get(j + 1) == 1) {
- neighbors.add(new int[]{i, j + 1});
- }
- return neighbors;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement