51. N 皇后

52. N皇后 II

  1. class Solution {
  2. public List<List<String>> solveNQueens(int n) {
  3. List<List<String>> result=new ArrayList<>();
  4. char[][] board=new char[n][n];
  5. for(int i=0;i<n;i++){
  6. for(int j=0;j<n;j++){
  7. board[i][j]='.';
  8. }
  9. }
  10. dfs(0,n,board,result);
  11. return result;
  12. }
  13. private void dfs(int i,int n,char[][] board,List<List<String>> result){
  14. if(i==n){
  15. //generate answer
  16. List<String> path=new ArrayList<>();
  17. for(int x=0;x<n;x++){
  18. StringBuilder sb=new StringBuilder();
  19. for(int y=0;y<n;y++){
  20. sb.append(board[x][y]);
  21. }
  22. path.add(sb.toString());
  23. }
  24. result.add(new ArrayList<>(path));
  25. return;
  26. }
  27. for(int j=0;j<n;j++){
  28. if(inRightPlace(i, j, board)){
  29. board[i][j]='Q';
  30. dfs(i+1,n,board,result);
  31. board[i][j]='.';
  32. }
  33. }
  34. }
  35. private boolean inRightPlace(int i,int j,char[][] board){
  36. //row
  37. for(int y=0;y<board.length;y++){
  38. if(board[i][y]=='Q') return false;
  39. }
  40. //col
  41. for(int x=0;x<board.length;x++){
  42. if(board[x][j]=='Q') return false;
  43. }
  44. //k=1
  45. for(int x=0;x<board.length;x++){
  46. int y=x-i+j;
  47. if(y<board.length&&y>=0&&board[x][y]=='Q') return false;
  48. }
  49. //k=-1
  50. for(int x=0;x<board.length;x++){
  51. int y=i+j-x;
  52. if(y<board.length&&y>=0&&board[x][y]=='Q') return false;
  53. }
  54. return true;
  55. }
  56. }