Skip to content

Commit c16cfc5

Browse files
committed
complete number of islands
1 parent 069eb4b commit c16cfc5

File tree

2 files changed

+44
-9
lines changed

2 files changed

+44
-9
lines changed

leetcode/number-of-islands.go

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,51 @@ var (
88
height int
99
)
1010

11+
const (
12+
unVisited = 0
13+
visited = 1
14+
)
15+
16+
var visitedMark [][]int
17+
1118
func numIslands(grid [][]byte) int {
1219
height = len(grid)
1320
if height == 0 {
1421
return 0
1522
}
1623
width = len(grid[0])
24+
visitedMark = make([][]int, height)
25+
for i := 0; i < height; i++ {
26+
visitedMark[i] = make([]int, width)
27+
}
1728
total = 0
29+
30+
for i := 0; i < height; i++ {
31+
for k := 0; k < width; k++ {
32+
if grid[i][k] == '1' && visitedMark[i][k] == unVisited {
33+
dfs(grid, i, k)
34+
total++
35+
}
36+
}
37+
}
38+
1839
return total
1940
}
2041

21-
func dfs(grid [][]int, x, y int) {
42+
func dfs(grid [][]byte, x, y int) {
43+
if x == height || y == width || x < 0 || y < 0 {
44+
return
45+
}
46+
if visitedMark[x][y] == visited {
47+
return
48+
}
49+
visitedMark[x][y] = visited
50+
if grid[x][y] == '0' {
51+
return
52+
}
2253

54+
dfs(grid, x-1, y)
55+
dfs(grid, x, y-1)
56+
dfs(grid, x+1, y)
57+
dfs(grid, x, y+1)
2358
}

leetcode/number-of-islands_test.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,18 @@ func Test_numIsLands(t *testing.T) {
99
}{
1010
{
1111
input: [][]byte{
12-
[]byte{1, 1, 1, 1, 0},
13-
[]byte{1, 1, 0, 1, 0},
14-
[]byte{1, 1, 0, 0, 0},
15-
[]byte{0, 0, 0, 0, 0},
12+
[]byte{'1', '1', '1', '1', '0'},
13+
[]byte{'1', '1', '0', '1', '0'},
14+
[]byte{'1', '1', '0', '0', '0'},
15+
[]byte{'0', '0', '0', '0', '0'},
1616
},
1717
expect: 1,
1818
}, {
1919
input: [][]byte{
20-
[]byte{1, 1, 0, 0, 0},
21-
[]byte{1, 1, 0, 0, 0},
22-
[]byte{0, 0, 1, 0, 0},
23-
[]byte{0, 0, 0, 1, 1},
20+
[]byte{'1', '1', '0', '0', '0'},
21+
[]byte{'1', '1', '0', '0', '0'},
22+
[]byte{'0', '0', '1', '0', '0'},
23+
[]byte{'0', '0', '0', '1', '1'},
2424
},
2525
expect: 3,
2626
},

0 commit comments

Comments
 (0)