Given a 2d grid map of `'1'`s (land) and `'0'`s (water), count 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:
11110
11010
11000
00000

Output: 1
Example 2:

Input:
11000
11000
00100
00011

Output: 3``````

Solution 1 (DFS):

``````func numIslands(grid [][]byte) int {
lenX := len(grid)
if lenX == 0 {return 0}
lenY := len(grid[0])
count := 0;

for i:=0; i < lenX; i++ {
for j := 0; j < lenY; j++ {
if grid[i][j] == '1' {
count++;
dfs(&grid, i, j)
}

}
}

return count;

}
func dfs(grid *[][]byte, x, y int) {
lenX := len(*grid)
lenY := len((*grid)[0])
if x < 0 || y  < 00 || x >= lenX  || y >= lenY {
return
}
if (*grid)[x][y] == '1' {
(*grid)[x][y] = '0'
dfs(grid, x+1,y)
dfs(grid, x-1,y)
dfs(grid, x,y-1)
dfs(grid, x,y+1)
}
}

``````

Solution 2(union find):

``````type UnionFind struct{
Parent []int  // two dimensions compress to one dimension
Size []int
Count int
}

func(u *UnionFind) Init(grid *[][]byte) {
lenX := len(*grid)
lenY := len((*grid)[0])
size := lenX * lenY;
u.Parent = make([]int, size )
u.Size = make([]int, size)

for i:= 0; i < lenX; i++ {
for j:= 0; j < lenY; j++ {
node := i*lenY + j
if (*grid)[i][j] == '1' {
u.Parent[node] = node
u.Size[node] = 1
u.Count++

} else {
u.Parent[node] = -1  // mark '0' node's parent = -1
}
}
}
}
func(u *UnionFind) Union(a,b int) {
pa, pb := u.Find(a), u.Find(b)

if pa == pb {
return
}
bp := pa // bigger parent
sp := pb// smaller parent
if u.Size[pa] < u.Size[pb] {
bp = pb
sp = pa
}
u.Parent[sp] = u.Parent[bp]
u.Size[bp] += u.Size[sp]
}
func(u *UnionFind) Find(x int) int {
for u.Parent[x] != x  { // compress path while finding
u.Parent[x] = u.Parent[(u.Parent[x])]
x = u.Parent[x];
}
return x
}

func validNode (x,y,lenX,lenY int) bool{
return x >= 0 && y >= 0 && x < lenX && y < lenY
}

func numIslands(grid [][]byte) int {
lenX := len(grid)
if lenX == 0 {return 0}
lenY := len(grid[0])

u := UnionFind{}
// init grid graph,  mark '0' node's parent = -1  mark '1' node's parent = self
u.Init(&grid)
x, y:= []int{-1,1,0,0}, []int{0,0,-1,1}

// fmt.Println(u)
for i:= 0; i < lenX; i++ {
for j:= 0; j < lenY; j++ {
if grid[i][j] == '1' {
currentNode := i * lenY + j
for k := 0; k < 4; k++ {                   // 4 direction find '1'
nextX, nextY := i+x[k], j+y[k]
if  validNode(nextX, nextY, lenX, lenY) && grid[nextX][nextY] == '1' {
nextNode := (nextX) * lenY + nextY
if u.Find(nextNode) != u.Find(currentNode) {
u.Union(nextNode, currentNode)
u.Count--

}
}
}
}
}
}

return u.Count;

} ``````