Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 69103f6

Browse files
committed
Update0051.N皇后,添加C#
1 parent f134c39 commit 69103f6

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

‎problems/0051.N皇后.md‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -865,6 +865,60 @@ object Solution {
865865
}
866866
}
867867
```
868+
### C#
869+
```csharp
870+
public class Solution
871+
{
872+
public List<IList<string>> res = new();
873+
public IList<IList<string>> SolveNQueens(int n)
874+
{
875+
char[][] chessBoard = new char[n][];
876+
for (int i = 0; i < n; i++)
877+
{
878+
chessBoard[i] = new char[n];
879+
for (int j = 0; j < n; j++)
880+
{
881+
chessBoard[i][j] = '.';
882+
}
883+
}
884+
BackTracking(n, 0, chessBoard);
885+
return res;
886+
}
887+
public void BackTracking(int n, int row, char[][] chessBoard)
888+
{
889+
if (row == n)
890+
{
891+
res.Add(chessBoard.Select(x => new string(x)).ToList());
892+
return;
893+
}
894+
for (int col = 0; col < n; col++)
895+
{
896+
if (IsValid(row, col, chessBoard, n))
897+
{
898+
chessBoard[row][col] = 'Q';
899+
BackTracking(n, row + 1, chessBoard);
900+
chessBoard[row][col] = '.';
901+
}
902+
}
903+
}
904+
public bool IsValid(int row, int col, char[][] chessBoard, int n)
905+
{
906+
for (int i = 0; i < row; i++)
907+
{
908+
if (chessBoard[i][col] == 'Q') return false;
909+
}
910+
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--)
911+
{
912+
if (chessBoard[i][j] == 'Q') return false;
913+
}
914+
for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++)
915+
{
916+
if (chessBoard[i][j] == 'Q') return false;
917+
}
918+
return true;
919+
}
920+
}
921+
```
868922

869923
<p align="center">
870924
<a href="https://programmercarl.com/other/kstar.html" target="_blank">

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /