mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
Merge pull request #2405 from fwqaaq/patch-2
Update 0200.岛屿数量.广搜版.md for golang
This commit is contained in:
@ -199,7 +199,9 @@ class Solution {
|
|||||||
|
|
||||||
|
|
||||||
### Python
|
### Python
|
||||||
|
|
||||||
BFS solution
|
BFS solution
|
||||||
|
|
||||||
```python
|
```python
|
||||||
class Solution:
|
class Solution:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
@ -240,6 +242,7 @@ class Solution:
|
|||||||
|
|
||||||
```
|
```
|
||||||
### JavaScript
|
### JavaScript
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
var numIslands = function (grid) {
|
var numIslands = function (grid) {
|
||||||
let dir = [[0, 1], [1, 0], [-1, 0], [0, -1]]; // 四个方向
|
let dir = [[0, 1], [1, 0], [-1, 0], [0, -1]]; // 四个方向
|
||||||
@ -321,11 +324,53 @@ function numIslands2(grid: string[][]): number {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Go
|
||||||
|
|
||||||
|
```go
|
||||||
|
var DIRECTIONS = [4][2]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}}
|
||||||
|
|
||||||
|
func numIslands(grid [][]byte) int {
|
||||||
|
res := 0
|
||||||
|
|
||||||
|
visited := make([][]bool, len(grid))
|
||||||
|
for i := 0; i < len(grid); i++ {
|
||||||
|
visited[i] = make([]bool, len(grid[0]))
|
||||||
|
}
|
||||||
|
|
||||||
|
for i, rows := range grid {
|
||||||
|
for j, v := range rows {
|
||||||
|
if v == '1' && !visited[i][j] {
|
||||||
|
res++
|
||||||
|
bfs(grid, visited, i, j)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
func bfs(grid [][]byte, visited [][]bool, i, j int) {
|
||||||
|
queue := [][2]int{{i, j}}
|
||||||
|
visited[i][j] = true // 标记已访问,循环中标记会导致重复
|
||||||
|
for len(queue) > 0 {
|
||||||
|
cur := queue[0]
|
||||||
|
queue = queue[1:]
|
||||||
|
for _, d := range DIRECTIONS {
|
||||||
|
x, y := cur[0]+d[0], cur[1]+d[1]
|
||||||
|
if x < 0 || x >= len(grid) || y < 0 || y >= len(grid[0]) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if grid[x][y] == '1' && !visited[x][y] {
|
||||||
|
visited[x][y] = true
|
||||||
|
queue = append(queue, [2]int{x, y})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### Rust
|
### Rust
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
|
|
||||||
use std::collections::VecDeque;
|
use std::collections::VecDeque;
|
||||||
impl Solution {
|
impl Solution {
|
||||||
const DIRECTIONS: [(i32, i32); 4] = [(0, 1), (1, 0), (-1, 0), (0, -1)];
|
const DIRECTIONS: [(i32, i32); 4] = [(0, 1), (1, 0), (-1, 0), (0, -1)];
|
||||||
|
Reference in New Issue
Block a user