-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0200.go
130 lines (115 loc) · 2.6 KB
/
0200.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
// Source: https://leetcode.com/problems/number-of-islands
// Title: Number of Islands
// Difficulty: Medium
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
//
// 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 1:
//
// Input: grid = [
// ["1","1","1","1","0"],
// ["1","1","0","1","0"],
// ["1","1","0","0","0"],
// ["0","0","0","0","0"]
// ]
// Output: 1
//
// Example 2:
//
// Input: grid = [
// ["1","1","0","0","0"],
// ["1","1","0","0","0"],
// ["0","0","1","0","0"],
// ["0","0","0","1","1"]
// ]
// Output: 3
//
// Constraints:
//
// m == grid.length
// n == grid[i].length
// 1 <= m, n <= 300
// grid[i][j] is '0' or '1'.
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
package main
// Union-Find
type unionFind struct {
parent []int
rank []int
count int // number of connected components
}
func newUnionFind(grid [][]byte) *unionFind {
m := len(grid)
n := len(grid[0])
count := 0
parent := make([]int, m*n)
rank := make([]int, m*n)
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
k := i*n + j
if grid[i][j] == '1' {
parent[k] = k
count++
} else {
parent[k] = -1
}
rank[k] = 0
}
}
return &unionFind{
parent: parent,
rank: rank,
count: count,
}
}
func (u *unionFind) find(i int) int { // path compression
if i != u.parent[i] {
u.parent[i] = u.find(u.parent[i])
}
return u.parent[i]
}
func (u *unionFind) union(x, y int) { // union with rank
x = u.find(x)
y = u.find(y)
if x == y {
return
}
if u.rank[x] > u.rank[y] {
x, y = y, x
}
u.parent[x] = y
if u.rank[x] == u.rank[y] {
u.rank[x]++
}
u.count--
}
func numIslands(grid [][]byte) int {
m := len(grid)
n := len(grid[0])
uf := newUnionFind(grid)
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
k := i*n + j
if grid[i][j] == '1' {
grid[i][j] = '0'
if i-1 >= 0 && grid[i-1][j] == '1' {
uf.union(k, (i-1)*n+j)
}
if i+1 < m && grid[i+1][j] == '1' {
uf.union(k, (i+1)*n+j)
}
if j-1 >= 0 && grid[i][j-1] == '1' {
uf.union(k, i*n+(j-1))
}
if j+1 < n && grid[i][j+1] == '1' {
uf.union(k, i*n+(j+1))
}
}
}
}
return uf.count
}