|
| 1 | +//https://leetcode.com/problems/number-of-islands-ii/ |
| 2 | + |
| 3 | +package number_of_islands_ii |
| 4 | + |
| 5 | +func numIslands2(height int, width int, positions [][]int) []int { |
| 6 | + ds := NewDisjointSet(height * width) |
| 7 | + seen := make(map[int]bool) |
| 8 | + result := make([]int, len(positions)) |
| 9 | + totalGroup := 0 |
| 10 | + for index, pos := range positions { |
| 11 | + row := pos[0] |
| 12 | + col := pos[1] |
| 13 | + curId := row*width + col |
| 14 | + if seen[curId] { |
| 15 | + result[index] = totalGroup |
| 16 | + continue |
| 17 | + } |
| 18 | + seen[curId] = true |
| 19 | + neighborGroups := make(map[int]bool, 0) |
| 20 | + if row > 0 && seen[(row-1)*width+col] { |
| 21 | + neighborGroups[ds.Find((row-1)*width+col)] = true |
| 22 | + } |
| 23 | + if col > 0 && seen[row*width+col-1] { |
| 24 | + neighborGroups[ds.Find(row*width+col-1)] = true |
| 25 | + } |
| 26 | + if row < height-1 && seen[(row+1)*width+col] { |
| 27 | + neighborGroups[ds.Find((row+1)*width+col)] = true |
| 28 | + } |
| 29 | + if col < width-1 && seen[row*width+col+1] { |
| 30 | + neighborGroups[ds.Find(row*width+col+1)] = true |
| 31 | + } |
| 32 | + curGroup := ds.Find(curId) |
| 33 | + |
| 34 | + if len(neighborGroups) == 0 { |
| 35 | + totalGroup++ |
| 36 | + } else { |
| 37 | + for group := range neighborGroups { |
| 38 | + ds.Union(curGroup, group) |
| 39 | + } |
| 40 | + mergedGroups := make(map[int]bool, 0) |
| 41 | + for group := range neighborGroups { |
| 42 | + mergedGroups[ds.Find(group)] = true |
| 43 | + } |
| 44 | + totalGroup -= len(neighborGroups) - len(mergedGroups) |
| 45 | + } |
| 46 | + result[index] = totalGroup |
| 47 | + } |
| 48 | + return result |
| 49 | +} |
| 50 | + |
| 51 | +type DisjointSet struct { |
| 52 | + parent []int |
| 53 | + rank []int |
| 54 | +} |
| 55 | + |
| 56 | +func NewDisjointSet(n int) *DisjointSet { |
| 57 | + parent := make([]int, n) |
| 58 | + rank := make([]int, n) |
| 59 | + for i := 0; i < n; i++ { |
| 60 | + parent[i] = i |
| 61 | + } |
| 62 | + return &DisjointSet{parent, rank} |
| 63 | +} |
| 64 | + |
| 65 | +func (ds *DisjointSet) Find(x int) int { |
| 66 | + if ds.parent[x] != x { |
| 67 | + ds.parent[x] = ds.Find(ds.parent[x]) |
| 68 | + } |
| 69 | + return ds.parent[x] |
| 70 | +} |
| 71 | + |
| 72 | +func (ds *DisjointSet) Union(x int, y int) { |
| 73 | + xRoot := ds.Find(x) |
| 74 | + yRoot := ds.Find(y) |
| 75 | + if xRoot == yRoot { |
| 76 | + return |
| 77 | + } |
| 78 | + if ds.rank[xRoot] < ds.rank[yRoot] { |
| 79 | + ds.parent[xRoot] = yRoot |
| 80 | + } else if ds.rank[xRoot] > ds.rank[yRoot] { |
| 81 | + ds.parent[yRoot] = xRoot |
| 82 | + } else { |
| 83 | + ds.parent[yRoot] = xRoot |
| 84 | + ds.rank[xRoot]++ |
| 85 | + } |
| 86 | +} |
0 commit comments