Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8823181

Browse files
authored
Update 1020.飞地的数量.md
1 parent 4f1c28d commit 8823181

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

‎problems/1020.飞地的数量.md‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -545,6 +545,66 @@ func dfs(grid [][]int, i, j int) {
545545
}
546546
```
547547

548+
bfs:
549+
550+
```go
551+
var DIRECTIONS = [4][2]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}}
552+
var count int = 0
553+
554+
func numEnclaves(grid [][]int) int {
555+
rows, cols := len(grid), len(grid[0])
556+
//
557+
for i := range grid[0] {
558+
if grid[0][i] == 1 {
559+
bfs(grid, 0, i)
560+
}
561+
if grid[rows-1][i] == 1 {
562+
bfs(grid, rows-1, i)
563+
}
564+
}
565+
//
566+
for j := range grid {
567+
if grid[j][0] == 1 {
568+
bfs(grid, j, 0)
569+
}
570+
if grid[j][cols-1] == 1 {
571+
bfs(grid, j, cols-1)
572+
}
573+
}
574+
count = 0
575+
for i := range grid {
576+
for j := range grid[0] {
577+
if grid[i][j] == 1 {
578+
bfs(grid, i, j)
579+
}
580+
}
581+
}
582+
return count
583+
}
584+
585+
func bfs(grid [][]int, i, j int) {
586+
queue := [][]int{}
587+
queue = append(queue, []int{i, j})
588+
grid[i][j] = 0
589+
count++
590+
for len(queue) > 0 {
591+
cur := queue[0]
592+
queue = queue[1:]
593+
for _, d := range DIRECTIONS {
594+
x, y := cur[0]+d[0], cur[1]+d[1]
595+
if x < 0 || x >= len(grid) || y < 0 || y >= len(grid[0]) {
596+
continue
597+
}
598+
if grid[x][y] == 1 {
599+
count++
600+
queue = append(queue, []int{x, y})
601+
grid[x][y] = 0
602+
}
603+
}
604+
}
605+
}
606+
```
607+
548608
### Rust
549609

550610
dfs:

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /