Leetcode 51: N-Queens
le is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q'
and '.'
both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]
1 public class Solution { 2 public IList<IList<string>> SolveNQueens(int n) { 3 var result = new List<IList<string>>(); 4 5 if (n < 1) return result; 6 7 var board = new int[n, n]; 8 9 CanSolve(board, n, 0, result); 10 11 return result; 12 } 13 14 private bool CanSolve(int[,] board, int n, int row, IList<IList<string>> results) 15 { 16 if (row >= n) 17 { 18 var result = new List<string>(); 19 for (int i = 0; i < n; i++) 20 { 21 var sb = new StringBuilder(); 22 for (int j = 0; j < n; j++) 23 { 24 sb.Append(board[i, j] == 0 ? '.' : 'Q'); 25 } 26 27 result.Add(sb.ToString()); 28 } 29 30 results.Add(result); 31 32 return true; 33 } 34 35 bool canSolve = false; 36 37 for (int j = 0; j < n; j++) 38 { 39 if (IsValidPosition(board, n, row, j)) 40 { 41 board[row, j] = 1; 42 if (CanSolve(board, n, row + 1, results)) 43 { 44 canSolve = true; 45 } 46 board[row, j] = 0; 47 } 48 } 49 50 return canSolve; 51 } 52 53 private bool IsValidPosition(int[,] board, int n, int row, int col) 54 { 55 // check whether we can put a queen at board[row, j] 56 // 1. whether it has alreay a queen on this column 57 for (int i = 0; i < row; i++) 58 { 59 if (board[i, col] == 1) return false; 60 } 61 62 // check backward diagonal 63 int r = row - 1, c = col - 1; 64 while (r >= 0 && c >= 0) 65 { 66 if (board[r, c] == 1) return false; 67 r--; 68 c--; 69 } 70 71 // check forward diagonal 72 r = row - 1; 73 c = col + 1; 74 while (r >= 0 && c < n) 75 { 76 if (board[r, c] == 1) return false; 77 r--; 78 c++; 79 } 80 81 return true; 82 } 83 }