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) to a land. Given a list of positions to operate, count the number of the islands in each addland operation. An island is surrounded by water and are formed by connecting adjacent lands horizontally or vertically. Assume all four edges of the grid is all surrounded by water.
Example:
Given m = 3, n = 3
, positions = [[0,0], [0,1], [1,2], [2,1]]
.
Initially, the 2d grid is grid
filled with water. (Assume 0 represents water and 1 represents land).
0 0 00 0 00 0 0
Operation #1: Addland (0, 0) turns the water at Grid[0][0] to a land.
1 0 XX 0 0 number of Islands = 10 0 0
Operation #2: Addland (0, 1) turns the water at Grid[0][1] to a land.
1 1 XX 0 0 Number of Islands = 10 0 0
Operation #3: Addland (1, 2) turns the water at Grid[1][2] to a land.
1 1 XX 0 1 number of Islands = 20 0 0
Operation #4: Addland (2, 1) turns the water at Grid[2][1] to a land.
1 1 XX 0 1 number of Islands = 30 1 0
We return the result as an array:[1, 1, 2, 3]
Challenge:
Can 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, in an undirected Graph"
1 Public classSolution {2 int[] moves =New int[][]{{1,0},{-1,0},{0,1},{0,-1}};3 4 PublicList<integer> NumIslands2 (intMintNint[] positions) {5list<integer> res =NewArraylist<integer>();6 if(positions.length==0)returnRes;7 8 int[] Grid =New int[m][n];9List<integer> rootlist =NewArraylist<integer>();
This was important:we need make sure root 1 are on index 1.TenRootlist.add (0); One intindex = 1; A intCount = 0; - - for(inti=0;i<positions.length;i++){ the int[] p =Positions[i]; - for(intj=0;j<4;j++){ - int[] Next =New int[]{p[0]+moves[j][0],p[1]+moves[j][1]}; - if(next[0]>=0 && next[0]<m && next[1]>=0 && next[1]<n && grid[next[0]][next[ 1]]!=0){ + //if p have not assigned index - if(grid[p[0]][p[1]]==0){ +GRID[P[0]][P[1]] = grid[next[0]][next[1]]; A}Else { at //merge root indexs of P and next. - intROOTP = FindRoot (rootlist,grid[p[0]][p[1]]); - intRootnext = FindRoot (rootlist,grid[next[0]][next[1]]); - if(rootp!=Rootnext) { - Rootlist.set (ROOTNEXT,ROOTP); -count--; in } - } to } + } - //If no merge happens, assign a new root index to P the if(grid[p[0]][p[1]]==0){ * Rootlist.add (index); $GRID[P[0]][P[1]] = index++; Panax Notoginsengcount++; - } the + Res.add (count); A } the + returnRes; - } $ $ Public intFindRoot (list<integer> rootlist,intID) { - while(Rootlist.get (id)! =ID) { - intRoot =rootlist.get (ID); the Rootlist.set (Id,rootlist.get (root)); -ID =rootlist.get (ID);Wuyi } the returnID; - } Wu - About}
Leetcode-number of Islands II