Advertisement
yimengael

Find Largest Island

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