标签:
A 2d grid map of m
rows and n
columns is initially filled with water. We may perform an addLand operation which turns the water at position (row, col) into a land. Given a list of positions to operate, count the number of islands after each addLand operation. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example:
Given m = 3, n = 3
, positions = [[0,0], [0,1], [1,2], [2,1]]
.
Initially, the 2d grid grid
is filled with water. (Assume 0 represents water and 1 represents land).
0 0 0 0 0 0 0 0 0
Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land.
1 0 0 0 0 0 Number of islands = 1 0 0 0
Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land.
1 1 0 0 0 0 Number of islands = 1 0 0 0
Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land.
1 1 0 0 0 1 Number of islands = 2 0 0 0
Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land.
1 1 0 0 0 1 Number of islands = 3 0 1 0
We return the result as an array: [1, 1, 2, 3]
Challenge:
Can you do it in time complexity O(k log mn), where k is the length of the positions
?
Solution:
the solution is similar to "Number of Connected Components in an Undirected Graph"
1 public class Solution { 2 int[][] moves = new int[][]{{1,0},{-1,0},{0,1},{0,-1}}; 3 4 public List<Integer> numIslands2(int m, int n, int[][] positions) { 5 List<Integer> res = new ArrayList<Integer>(); 6 if (positions.length==0) return res; 7 8 int[][] grid = new int[m][n]; 9 List<Integer> rootList = new ArrayList<Integer>();
// This is IMPORTANT: we need make sure root 1 is on index 1. 10 rootList.add(0); 11 int index = 1; 12 int count = 0; 13 14 for (int i=0;i<positions.length;i++){ 15 int[] p = positions[i]; 16 for (int j=0;j<4;j++){ 17 int[] next = new int[]{p[0]+moves[j][0],p[1]+moves[j][1]}; 18 if (next[0]>=0 && next[0]<m && next[1]>=0 && next[1]<n && grid[next[0]][next[1]]!=0){ 19 // if p has not assigned index 20 if (grid[p[0]][p[1]]==0){ 21 grid[p[0]][p[1]] = grid[next[0]][next[1]]; 22 } else { 23 // merge root indexs of p and next. 24 int rootP = findRoot(rootList,grid[p[0]][p[1]]); 25 int rootNext = findRoot(rootList,grid[next[0]][next[1]]); 26 if (rootP!=rootNext){ 27 rootList.set(rootNext,rootP); 28 count--; 29 } 30 } 31 } 32 } 33 // if no merge happens, assign a new root index to p 34 if (grid[p[0]][p[1]]==0){ 35 rootList.add(index); 36 grid[p[0]][p[1]] = index++; 37 count++; 38 } 39 40 res.add(count); 41 } 42 43 return res; 44 } 45 46 public int findRoot(List<Integer> rootList, int id){ 47 while (rootList.get(id)!=id){ 48 int root = rootList.get(id); 49 rootList.set(id,rootList.get(root)); 50 id = rootList.get(id); 51 } 52 return id; 53 } 54 55 56 }
标签:
原文地址:http://www.cnblogs.com/lishiblog/p/5772630.html