Advertisement
blwrvksrblv

827. Making A Large Island

Feb 19th, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.20 KB | None | 0 0
  1. // Time: O(n2), Space: O(n2)
  2. // https://leetcode.com/problems/making-a-large-island/discuss/127015/C%2B%2B-O(n*m)-15-ms-colorful-islands
  3. class Solution {
  4.     public int largestIsland(int[][] grid) {
  5.         if (grid == null || grid.length == 0 || grid[0].length == 0) {
  6.             return 0;
  7.         }
  8.        
  9.         int c = 2;
  10.         int n = grid.length;
  11.         int m = grid[0].length;
  12.         HashMap<Integer, Integer> islandCount = new HashMap<>();
  13.         int[][] dirs = { {0,1}, {0,-1}, {1,0}, {-1,0} };
  14.        
  15.         for (int i=0; i<n; i++) {
  16.             for (int j=0; j<n; j++) {
  17.                 if (grid[i][j] == 1) {
  18.                     dfs(grid, i, j, n, m, c, islandCount, dirs);
  19.                     c++;
  20.                 }
  21.             }
  22.         }
  23.        
  24.         int res = 0;
  25.         for (int i=0; i<n; i++) {
  26.             for(int j=0; j<m; j++) {
  27.                 if (grid[i][j] == 0) {
  28.                     HashSet<Integer> seen = new HashSet<>();
  29.                     int tmp = 1;
  30.                    
  31.                     for (int[] dir : dirs) {
  32.                         int x = i + dir[0];
  33.                         int y = j + dir[1];
  34.                        
  35.                         if (x<0 || x>=n || y<0 || y>=m || grid[x][y] == 0 || seen.contains(grid[x][y])) {
  36.                             continue;
  37.                         }
  38.                        
  39.                         tmp += islandCount.get(grid[x][y]);
  40.                         seen.add(grid[x][y]);
  41.                     }
  42.                    
  43.                     res = Math.max(res, tmp);
  44.                 } else {
  45.                     res = Math.max(res, islandCount.get(grid[i][j]));
  46.                 }
  47.             }
  48.         }
  49.        
  50.         return res;
  51.     }
  52.    
  53.     public void dfs(int[][] grid, int i, int j, int n, int m, int c, HashMap<Integer, Integer> islandCount, int[][] dirs) {
  54.         if (i<0 || i>=n || j<0 || j>=m || grid[i][j] != 1) {
  55.             return;
  56.         }
  57.        
  58.         grid[i][j] = c;
  59.         islandCount.put(c, islandCount.getOrDefault(c,0)+1);
  60.        
  61.         for (int[] dir : dirs) {
  62.             dfs(grid, i + dir[0], j + dir[1], n, m, c, islandCount, dirs);
  63.         }
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement