From 69103f6c86fddc3d10ffe921dce8b93e259f71e2 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Sat, 23 Dec 2023 10:11:06 +0800 Subject: [PATCH] =?UTF-8?q?Update0051.N=E7=9A=87=E5=90=8E=EF=BC=8C?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0051.N皇后.md | 54 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/problems/0051.N皇后.md b/problems/0051.N皇后.md index f6290793..1e108540 100644 --- a/problems/0051.N皇后.md +++ b/problems/0051.N皇后.md @@ -865,6 +865,60 @@ object Solution { } } ``` +### C# +```csharp +public class Solution +{ + public List> res = new(); + public IList> SolveNQueens(int n) + { + char[][] chessBoard = new char[n][]; + for (int i = 0; i < n; i++) + { + chessBoard[i] = new char[n]; + for (int j = 0; j < n; j++) + { + chessBoard[i][j] = '.'; + } + } + BackTracking(n, 0, chessBoard); + return res; + } + public void BackTracking(int n, int row, char[][] chessBoard) + { + if (row == n) + { + res.Add(chessBoard.Select(x => new string(x)).ToList()); + return; + } + for (int col = 0; col < n; col++) + { + if (IsValid(row, col, chessBoard, n)) + { + chessBoard[row][col] = 'Q'; + BackTracking(n, row + 1, chessBoard); + chessBoard[row][col] = '.'; + } + } + } + public bool IsValid(int row, int col, char[][] chessBoard, int n) + { + for (int i = 0; i < row; i++) + { + if (chessBoard[i][col] == 'Q') return false; + } + for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) + { + if (chessBoard[i][j] == 'Q') return false; + } + for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) + { + if (chessBoard[i][j] == 'Q') return false; + } + return true; + } +} +```