Making A Large Island
阿新 • • 發佈:2018-12-25
In a 2D grid of 0
s and 1
s, we change at most one 0
to a 1
.
After, what is the size of the largest island? (An island is a 4-directionally connected group of 1
s).
Example 1:
Input: [[1, 0], [0, 1]] Output: 3 Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
Example 2:
Input: [[1, 1], [1, 0]] Output: 4 Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.
Example 3:
Input: [[1, 1], [1, 1]] Output: 4 Explanation: Can't change any 0 to 1, only one island with area = 4.
Notes:
1 <= grid.length = grid[0].length <= 50
0 <= grid[i][j] <= 1
.
題目理解:
給定一個只含0,1的矩陣,將所有連線的1成為一個島嶼,1的數目代表島嶼的大小,問,如果最多將一個位置的0改為1,那麼能夠得到的最大的島嶼面積是多少
解題思路:
大致的思路是,首先遍歷整個矩陣,找出所有的島嶼;然後再次遍歷矩陣,分析其中所有的0,將0四周的所有島嶼面積相加,找出最大值。在實現方式上,可以使用並查集的方式,將屬於一個島嶼的位置對映到一個head上,第二次遍歷的時候,只要四周的1不屬於同一個島嶼,就將其面積相加,取得最大值即可
class Solution { Node[][] root; int row, col; class Node{ int x, y, count; public Node(int a, int b, int c) { x = a; y = b; count = c; } } public int largestIsland(int[][] grid) { row = grid.length; if(row == 0) return 0; col = grid[0].length; root = new Node[row][col]; for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { root[i][j] = new Node(i, j, grid[i][j]); } } int res = 0; for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { if(grid[i][j] == 0) continue; if(i > 0 && grid[i - 1][j] == 1) { Node root_cur = find(i - 1, j); root_cur.x = i; root_cur.y = j; root[i][j].count += root_cur.count; } if(j > 0 && grid[i][j - 1] == 1) { Node root_cur = find(i, j - 1); if(root_cur.x != i || root_cur.y != j) { root_cur.x = i; root_cur.y = j; root[i][j].count += root_cur.count; } } res = Math.max(res, root[i][j].count); } } Set<Integer> set = new HashSet<Integer>(); int sum, pos; Node root_cur; for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { if(grid[i][j] == 1) continue; set.clear(); sum = 1; if(i > 0 && grid[i - 1][j] == 1) { root_cur = find(i - 1, j); pos = root_cur.x * col + root_cur.y; sum += root_cur.count; set.add(pos); } if(i + 1 < row && grid[i + 1][j] == 1) { root_cur = find(i + 1, j); pos = root_cur.x * col + root_cur.y; if(!set.contains(pos)) { sum += root_cur.count; set.add(pos); } } if(j - 1 > -1 && grid[i][j - 1] == 1) { root_cur = find(i, j - 1); pos = root_cur.x * col + root_cur.y; if(!set.contains(pos)) { sum += root_cur.count; set.add(pos); } } if(j + 1 < col && grid[i][j + 1] == 1) { root_cur = find(i, j + 1); pos = root_cur.x * col + root_cur.y; if(!set.contains(pos)) { sum += root_cur.count; set.add(pos); } } res = Math.max(res, sum); } } return res; } public Node find(int x, int y) { Node it = root[x][y]; if(x == it.x && y == it.y) return it; return find(it.x, it.y); } }