Advertisement
yimengael

Find Largest Island - Solved

Mar 7th, 2022
1,181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.17 KB | None | 0 0
  1.  
  2.     static Integer max_island_size(ArrayList<ArrayList<Integer>> grid) {
  3.         int nr = grid.size();
  4.         int nc = grid.get(0).size();
  5.        
  6.         int[][] visited = new int[nr][nc];
  7.        
  8.         int max_size = 0;
  9.         for (int i = 0; i < nr; i++) {
  10.             for (int j = 0; j < nc; j++) {
  11.                 if (visited[i][j] == 0 && grid.get(i).get(j) == 1) {
  12.                     int curr_size = bfs(i, j, visited, grid);
  13.                     max_size = Math.max(max_size, curr_size);
  14.                 }
  15.             }
  16.         }
  17.        
  18.         return max_size;
  19.     }
  20.    
  21.     static int bfs(int i, int j, int[][] visited, ArrayList<ArrayList<Integer>> grid) {
  22.         int nr = grid.size();
  23.         int nc = grid.get(0).size();
  24.        
  25.         int count = 1;
  26.         Queue<int[]> q = new LinkedList<int[]>();
  27.         q.offer(new int[]{i,j});
  28.         visited[i][j] = 1;
  29.         while (!q.isEmpty()) {
  30.             int[] curr = q.poll();
  31.             for (int[] neighbor : list_of_neighbors(curr[0], curr[1], grid)) {
  32.                 if (visited[neighbor[0]][neighbor[1]] == 0) {
  33.                     q.offer(neighbor);
  34.                     visited[neighbor[0]][neighbor[1]] = 1;
  35.                     count++;
  36.                 }
  37.             }
  38.         }
  39.        
  40.         return count;
  41.     }
  42.    
  43.     static ArrayList<int[]> list_of_neighbors(int i, int j, ArrayList<ArrayList<Integer>> grid) {
  44.         int nr = grid.size();
  45.         int nc = grid.get(0).size();
  46.        
  47.         ArrayList<int[]> neighbors = new ArrayList<int[]>();
  48.        
  49.         if (i - 1 >= 0 && i - 1 <= nr - 1 && grid.get(i - 1).get(j) == 1) {
  50.             neighbors.add(new int[]{i - 1, j});
  51.         }
  52.        
  53.         if (i + 1 >= 0 && i + 1 <= nr - 1 && grid.get(i + 1).get(j) == 1) {
  54.             neighbors.add(new int[]{i + 1, j});
  55.         }
  56.        
  57.         if (j - 1 >= 0 && j - 1 <= nc - 1 && grid.get(i).get(j - 1) == 1) {
  58.             neighbors.add(new int[]{i, j - 1});
  59.         }
  60.        
  61.         if (j + 1 >= 0 && j + 1 <= nc - 1 && grid.get(i).get(j + 1) == 1) {
  62.             neighbors.add(new int[]{i, j + 1});
  63.         }
  64.        
  65.         return neighbors;
  66.     }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement