Skip to content

Commit

Permalink
添加 0051.N皇后 Rust版本
Browse files Browse the repository at this point in the history
添加 0051.N皇后 Rust版本
  • Loading branch information
cezarbbb committed Jul 24, 2022
1 parent f50d606 commit 8e65f2e
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions problems/0051.N皇后.md
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,56 @@ func solveNQueens(_ n: Int) -> [[String]] {
}
```

### Rust

```Rust
impl Solution {
fn is_valid(row: usize, col: usize, chessboard: &mut Vec<Vec<char>>, n: usize) -> bool {
let mut i = 0 as usize;
while i < row {
if chessboard[i][col] == 'Q' { return false; }
i += 1;
}
let (mut i, mut j) = (row as i32 - 1, col as i32 - 1);
while i >= 0 && j >= 0 {
if chessboard[i as usize][j as usize] == 'Q' { return false; }
i -= 1;
j -= 1;
}
let (mut i, mut j) = (row as i32 - 1, col as i32 + 1);
while i >= 0 && j < n as i32 {
if chessboard[i as usize][j as usize] == 'Q' { return false; }
i -= 1;
j += 1;
}
return true;
}
fn backtracking(result: &mut Vec<Vec<String>>, n: usize, row: usize, chessboard: &mut Vec<Vec<char>>) {
if row == n {
let mut chessboard_clone: Vec<String> = Vec::new();
for i in chessboard {
chessboard_clone.push(i.iter().collect::<String>());
}
result.push(chessboard_clone);
return;
}
for col in 0..n {
if Self::is_valid(row, col, chessboard, n) {
chessboard[row][col] = 'Q';
Self::backtracking(result, n, row + 1, chessboard);
chessboard[row][col] = '.';
}
}
}
pub fn solve_n_queens(n: i32) -> Vec<Vec<String>> {
let mut result: Vec<Vec<String>> = Vec::new();
let mut chessboard: Vec<Vec<char>> = vec![vec!['.'; n as usize]; n as usize];
Self::backtracking(&mut result, n as usize, 0, &mut chessboard);
result
}
}
```

### C
```c
char ***ans;
Expand Down

0 comments on commit 8e65f2e

Please sign in to comment.