Skip to content

Commit a5a647e

Browse files
committed
number_of_islands
1 parent 2e73bbd commit a5a647e

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
158158
#### [191. Number of 1 Bits](https://github.com/hitzzc/go-leetcode/tree/master/number_of_1bits)
159159
#### [198. House Robber](https://github.com/hitzzc/go-leetcode/tree/master/house_robber)
160160
#### [199. Binary Tree Right Side View](https://github.com/hitzzc/go-leetcode/tree/master/binary_tree_right_side_view)
161+
#### [200. Number of Islands](https://github.com/hitzzc/go-leetcode/tree/master/number_of_islands)
161162

162163

163164

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package number_of_islands
2+
3+
func numIslands(grid [][]byte) int {
4+
if len(grid) == 0 || len(grid[0]) == 0 {
5+
return 0
6+
}
7+
var ret int
8+
visited := map[int]bool{}
9+
var k int
10+
for i := range grid {
11+
for j := range grid[i] {
12+
if grid[i][j] == '0' {
13+
continue
14+
}
15+
k = hash(i, j, len(grid[0]))
16+
if _, ok := visited[k]; ok {
17+
continue
18+
}
19+
ret++
20+
queue := []int{k}
21+
for len(queue) != 0 {
22+
top := queue[0]
23+
queue = queue[1:]
24+
row, col := top/len(grid[0]), top%len(grid[0])
25+
if row > 0 && grid[row-1][col] == '1' {
26+
k = hash(row-1, col, len(grid[0]))
27+
if _, ok := visited[k]; !ok {
28+
queue = append(queue, k)
29+
visited[k] = true
30+
}
31+
}
32+
if row < len(grid)-1 && grid[row+1][col] == '1' {
33+
k = hash(row+1, col, len(grid[0]))
34+
if _, ok := visited[k]; !ok {
35+
queue = append(queue, k)
36+
visited[k] = true
37+
}
38+
}
39+
if col > 0 && grid[row][col-1] == '1' {
40+
k = hash(row, col-1, len(grid[0]))
41+
if _, ok := visited[k]; !ok {
42+
queue = append(queue, k)
43+
visited[k] = true
44+
}
45+
}
46+
if col < len(grid[0])-1 && grid[row][col+1] == '1' {
47+
k = hash(row, col+1, len(grid[0]))
48+
if _, ok := visited[k]; !ok {
49+
queue = append(queue, k)
50+
visited[k] = true
51+
}
52+
}
53+
}
54+
}
55+
}
56+
return ret
57+
}
58+
59+
func hash(row, col, length int) int {
60+
return row*length + col
61+
}

0 commit comments

Comments
 (0)