@@ -240,6 +240,47 @@ class Solution:
240240
241241```
242242
243+ ### Rust
244+ 245+ ``` rust
246+ 247+ use std :: collections :: VecDeque ;
248+ impl Solution {
249+ const DIRECTIONS : [(i32 , i32 ); 4 ] = [(0 , 1 ), (1 , 0 ), (- 1 , 0 ), (0 , - 1 )];
250+ pub fn num_islands (grid : Vec <Vec <char >>) -> i32 {
251+ let mut visited = vec! [vec! [false ; grid [0 ]. len ()]; grid . len ()];
252+ let mut res = 0 ;
253+ for (i , chars ) in grid . iter (). enumerate () {
254+ for (j , & c ) in chars . iter (). enumerate () {
255+ if ! visited [i ][j ] && c == '1' {
256+ res += 1 ;
257+ Self :: bfs (& grid , & mut visited , (i as i32 , j as i32 ));
258+ }
259+ }
260+ }
261+ res
262+ }
263+ 264+ pub fn bfs (grid : & Vec <Vec <char >>, visited : & mut Vec <Vec <bool >>, (x , y ): (i32 , i32 )) {
265+ let mut queue = VecDeque :: new ();
266+ queue . push_back ((x , y ));
267+ visited [x as usize ][y as usize ] = true ;
268+ while let Some ((cur_x , cur_y )) = queue . pop_front () {
269+ for (dx , dy ) in Self :: DIRECTIONS {
270+ let (nx , ny ) = (cur_x + dx , cur_y + dy );
271+ if nx < 0 || nx >= grid . len () as i32 || ny < 0 || ny >= grid [0 ]. len () as i32 {
272+ continue ;
273+ }
274+ let (nx , ny ) = (nx as usize , ny as usize );
275+ if grid [nx ][ny ] == '1' && ! visited [nx ][ny ] {
276+ visited [nx ][ny ] = true ;
277+ queue . push_back ((nx as i32 , ny as i32 ));
278+ }
279+ }
280+ }
281+ }
282+ }
283+ ```
243284<p align =" center " >
244285<a href =" https://programmercarl.com/other/kstar.html " target =" _blank " >
245286 <img src =" ../pics/网站星球宣传海报.jpg " width =" 1000 " />
0 commit comments