mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Merge pull request #2246 from fwqaaq/fwqaaq-patch-shen
Update 0200.岛屿数量.深搜版.md about
This commit is contained in:
@ -279,6 +279,42 @@ class Solution:
|
|||||||
return result
|
return result
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Rust:
|
||||||
|
|
||||||
|
|
||||||
|
```rust
|
||||||
|
impl Solution {
|
||||||
|
const DIRECTIONS: [(i32, i32); 4] = [(0, 1), (1, 0), (-1, 0), (0, -1)];
|
||||||
|
pub fn num_islands(grid: Vec<Vec<char>>) -> i32 {
|
||||||
|
let mut visited = vec![vec![false; grid[0].len()]; grid.len()];
|
||||||
|
let mut res = 0;
|
||||||
|
for (i, chars) in grid.iter().enumerate() {
|
||||||
|
for (j, &c) in chars.iter().enumerate() {
|
||||||
|
if !visited[i][j] && c == '1' {
|
||||||
|
res += 1;
|
||||||
|
Self::dfs(&grid, &mut visited, (i as i32, j as i32));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn dfs(grid: &Vec<Vec<char>>, visited: &mut Vec<Vec<bool>>, (x, y): (i32, i32)) {
|
||||||
|
for (dx, dy) in Self::DIRECTIONS {
|
||||||
|
let (nx, ny) = (x + dx, y + dy);
|
||||||
|
if nx < 0 || nx >= grid.len() as i32 || ny < 0 || ny >= grid[0].len() as i32 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let (nx, ny) = (nx as usize, ny as usize);
|
||||||
|
if grid[nx][ny] == '1' && !visited[nx][ny] {
|
||||||
|
visited[nx][ny] = true;
|
||||||
|
Self::dfs(grid, visited, (nx as i32, ny as i32));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||||
|
Reference in New Issue
Block a user