Skip to content

Commit 6ed59e6

Browse files
committed
new soln
1 parent 891edac commit 6ed59e6

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

51.SolveNQueens.cs

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// 51. N-Queens
2+
// The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
3+
// Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.
4+
// Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.
5+
6+
// Example 1:
7+
// Input: n = 4
8+
// Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
9+
// Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above
10+
// Example 2:
11+
// Input: n = 1
12+
// Output: [["Q"]]
13+
14+
// Constraints:
15+
// 1 <= n <= 9
16+
17+
public class Solution {
18+
public IList<IList<string>> SolveNQueens(int n) {
19+
List<IList<String>> result = new List<IList<String>>();
20+
List<String> board = new List<String>();
21+
for(int i = 0; i<n; i++){
22+
StringBuilder row = new StringBuilder("");
23+
for(int j = 0; j < n; j++)
24+
row.Append(".");
25+
board.Add(row.ToString());
26+
}
27+
PlaceQueen(result, board,0);
28+
return result;
29+
}
30+
private void PlaceQueen(List<IList<String>> result, List<String> board,
31+
int rowIdx)
32+
{
33+
if(rowIdx == board.Count){
34+
result.Add(new List<String>(board));
35+
return;
36+
}
37+
for(int i = 0; i < board.Count; i++){
38+
if(IsSafe(board, rowIdx, i)){
39+
StringBuilder newRow = new StringBuilder(board[rowIdx]);
40+
newRow[i] = 'Q';
41+
board[rowIdx] = newRow.ToString();
42+
PlaceQueen(result, board, rowIdx+1);
43+
newRow[i] = '.';
44+
board[rowIdx] = newRow.ToString();
45+
}
46+
}
47+
}
48+
private bool IsSafe(List<String> board, int row, int col){
49+
for(int i = row; i >= 0; i--){
50+
if(board[i][col] == 'Q')
51+
return false;
52+
}
53+
for(int i = row, j = col; i >= 0 && j >= 0; i--, j--){
54+
if(board[i][j] == 'Q')
55+
return false;
56+
}
57+
for(int i = row, j = col; i >= 0 && j < board.Count; i--, j++){
58+
if(board[i][j] == 'Q')
59+
return false;
60+
}
61+
return true;
62+
}
63+
}

0 commit comments

Comments
 (0)