fork download
  1. public class Main {
  2.  
  3.  
  4.  
  5.  
  6. public static int [][]board=new int[8][8];
  7.  
  8. public static boolean isAttack(int i,int j) {
  9.  
  10. for(int y=0; y<8; y++) {
  11.  
  12. if(board[i][y]==1 || board[y][j]==1 ) {
  13. return true;
  14. }
  15. }
  16.  
  17. for(int x=0; x<=i; x++) {
  18. for(int y=0; y<=i; y++) {
  19. if((x+y==i+j) || (x-y==i-j)) {
  20. if(board[x][y]==1) {
  21. return true;
  22. }
  23. }
  24. }
  25. }
  26.  
  27.  
  28.  
  29. return false;
  30. }
  31.  
  32.  
  33.  
  34. public static boolean nqueen(int N) {
  35.  
  36.  
  37. if (N==0) {
  38.  
  39. return true;
  40. }
  41.  
  42.  
  43.  
  44.  
  45. for(int i=0; i<8; i++) {
  46. for(int j=0; j<8; j++) {
  47. if(!(isAttack(i,j)) && (board[i][j]!=1)) {
  48. board[i][j]=1;
  49.  
  50. if(nqueen(N-1)==true) {
  51. return true;
  52. }
  53.  
  54. board[i][j]=0;
  55. }
  56. }
  57. }
  58.  
  59.  
  60. return false;
  61. }
  62.  
  63.  
  64. public static void main(String []args) {
  65.  
  66. for(int []i : board) {
  67. for(int j : i) {
  68. j=0;
  69. }
  70. }
  71.  
  72.  
  73.  
  74. nqueen(8);
  75.  
  76.  
  77. for(int []i : board) {
  78. for(int j : i) {
  79. if(j==1) {
  80. System.out.print("Q"+" ");
  81. } else {
  82. System.out.print(j+" ");
  83. }
  84.  
  85. }
  86. System.out.println("");
  87. }
  88.  
  89.  
  90. }
  91. }
Success #stdin #stdout 0.12s 49008KB
stdin
Standard input is empty
stdout
Q 0 0 0 0 0 0 0 
0 0 Q 0 0 0 0 0 
0 0 0 0 Q 0 0 0 
0 0 0 0 0 0 Q 0 
0 0 0 0 0 0 0 Q 
0 0 0 Q 0 0 0 0 
0 Q 0 0 0 0 0 0 
0 0 0 0 0 Q 0 0