力扣51 N皇后
不能同行,同列,也不能同45度斜线
public void dfs(cheseborad,n,row) //n表示棋盘的大小,row表示现在列举到了第几行
{if(row==n){result.add();return;}for(int i=0;i<n;i++)//下一行的每一个数都可能被选中{if(isValid(row,i,cheseboard,n)==true)//第row行第i个位置,是否合法{cheseboard[row][i]='Q';dfs(cheseboard,n,row++);//下一行cheseboard[row][i]='.';}}
}
class Solution {List<List<String>> res = new ArrayList<>();public List<List<String>> solveNQueens(int n) {char[][] chessboard = new char[n][n];for(int i=0;i<n;i++){for(int j=0;j<n;j++){chessboard[i][j]='.';}}backTrack(n, 0, chessboard);return res;}public void backTrack(int n, int row, char[][] chessboard) {if (row == n) {res.add(Array2List(chessboard));return;}for (int col = 0;col < n; ++col) {if (isValid (row, col, n, chessboard)) {chessboard[row][col] = 'Q';backTrack(n, row+1, chessboard);chessboard[row][col] = '.';}}}public List Array2List(char[][] chessboard) {List<String> list = new ArrayList<>();for (char[] c : chessboard) {list.add(String.copyValueOf(c));}return list;}public boolean isValid(int row, int col, int n, char[][] chessboard) {// 检查列for (int i=0; i<row; ++i) { // 相当于剪枝if (chessboard[i][col] == 'Q') {return false;}}// 检查45度对角线for (int i=row-1, j=col-1; i>=0 && j>=0; i--, j--) {if (chessboard[i][j] == 'Q') {return false;}}// 检查135度对角线for (int i=row-1, j=col+1; i>=0 && j<=n-1; i--, j++) {if (chessboard[i][j] == 'Q') {return false;}}return true;}
}