@@ -558,6 +558,56 @@ func solveNQueens(_ n: Int) -> [[String]] {
558
558
}
559
559
```
560
560
561
+ ### Rust
562
+
563
+ ``` Rust
564
+ impl Solution {
565
+ fn is_valid (row : usize , col : usize , chessboard : & mut Vec <Vec <char >>, n : usize ) -> bool {
566
+ let mut i = 0 as usize ;
567
+ while i < row {
568
+ if chessboard [i ][col ] == 'Q' { return false ; }
569
+ i += 1 ;
570
+ }
571
+ let (mut i , mut j ) = (row as i32 - 1 , col as i32 - 1 );
572
+ while i >= 0 && j >= 0 {
573
+ if chessboard [i as usize ][j as usize ] == 'Q' { return false ; }
574
+ i -= 1 ;
575
+ j -= 1 ;
576
+ }
577
+ let (mut i , mut j ) = (row as i32 - 1 , col as i32 + 1 );
578
+ while i >= 0 && j < n as i32 {
579
+ if chessboard [i as usize ][j as usize ] == 'Q' { return false ; }
580
+ i -= 1 ;
581
+ j += 1 ;
582
+ }
583
+ return true ;
584
+ }
585
+ fn backtracking (result : & mut Vec <Vec <String >>, n : usize , row : usize , chessboard : & mut Vec <Vec <char >>) {
586
+ if row == n {
587
+ let mut chessboard_clone : Vec <String > = Vec :: new ();
588
+ for i in chessboard {
589
+ chessboard_clone . push (i . iter (). collect :: <String >());
590
+ }
591
+ result . push (chessboard_clone );
592
+ return ;
593
+ }
594
+ for col in 0 .. n {
595
+ if Self :: is_valid (row , col , chessboard , n ) {
596
+ chessboard [row ][col ] = 'Q' ;
597
+ Self :: backtracking (result , n , row + 1 , chessboard );
598
+ chessboard [row ][col ] = '.' ;
599
+ }
600
+ }
601
+ }
602
+ pub fn solve_n_queens (n : i32 ) -> Vec <Vec <String >> {
603
+ let mut result : Vec <Vec <String >> = Vec :: new ();
604
+ let mut chessboard : Vec <Vec <char >> = vec! [vec! ['.' ; n as usize ]; n as usize ];
605
+ Self :: backtracking (& mut result , n as usize , 0 , & mut chessboard );
606
+ result
607
+ }
608
+ }
609
+ ```
610
+
561
611
### C
562
612
``` c
563
613
char ***ans;
0 commit comments