Skip to content

Commit 3830785

Browse files
200. Number of Islands BFS
1 parent 41eac13 commit 3830785

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ Approach #1: DFS
4141

4242
//modifying grid, pass as a pointer
4343
//when try to change or get (len or value) dereference `(*grid)[i][j]==1`
44-
//Pass to recursive function, pass as it is
44+
//Pass grid to recursive function, pass as it is
4545
//byte use '' instead of ""
4646

4747
Approach #2: BFS
@@ -50,7 +50,7 @@ Approach #2: BFS
5050
3. add i and j pair into queue
5151
4. Mark visited by setting `grid[i][j]=0`
5252
5. while queue is empty
53-
1. Pop from queue
53+
1. dqueue pair i, j from queue
5454
2. change i and j to travel in all four direction
5555
3. check if they are in boundary of grid and value is 1
5656
1. add into the queue
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
//BFS
2+
3+
func numIslands(grid [][]byte) int {
4+
if len(grid) == 0 || len(grid[0]) == 0 {
5+
return 0
6+
}
7+
8+
landCount := 0
9+
queue := [][2]int{}
10+
for i := 0; i < len(grid); i++ {
11+
for j := 0; j < len(grid[i]); j++ {
12+
if grid[i][j] == '1' {
13+
landCount = landCount + 1
14+
grid[i][j] = '0'
15+
queue = append(queue, [2]int{i, j})
16+
offsets := [4][2]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}
17+
for len(queue) > 0 {
18+
currPair := queue[0]
19+
queue = queue[1:]
20+
row := len(grid)
21+
col := len(grid[0])
22+
for _, offset := range offsets {
23+
m := currPair[0] + offset[0]
24+
n := currPair[1] + offset[1]
25+
if m >= 0 && m < row && n >= 0 && n < col && grid[m][n] == '1' {
26+
grid[m][n] = '0'
27+
queue = append(queue, [2]int{m, n})
28+
}
29+
}
30+
}
31+
}
32+
}
33+
}
34+
return landCount
35+
}

0 commit comments

Comments
 (0)