Guest User

Untitled

a guest
Jul 23rd, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. /*
  2. ENG/15/138
  3. ET
  4. */
  5.  
  6. public class Queens {
  7. public static void main(String args[]) {
  8. int N = 8;
  9. int[][] chessboard = new int[N][N];
  10. solve(0, chessboard, N);
  11. for(int i = 0; i < N; i++) {
  12. for(int j = 0; j < N; j++) {
  13. if(chessboard[i][j]==1) System.out.print("Q ");
  14. else System.out.print("* ");
  15. }
  16. System.out.println();
  17. }
  18. }
  19.  
  20. static boolean solve(int row, int[][] chessboard, int N) {
  21. if(row>=N) return true;
  22. for(int position = 0; position < N; position++) {
  23. if(isValid(chessboard, row, position, N)) {
  24. chessboard[row][position] = 1;
  25. if(!solve(row+1, chessboard, N)) {
  26. chessboard[row][position] = 0;
  27. } else
  28. return true;
  29. }
  30. }
  31. return false;
  32. }
  33.  
  34. static boolean isValid(int[][] chessboard, int x, int y, int N) {
  35. int i, j;
  36. for(i = 0; i < x; i++)
  37. if(chessboard[i][y]==1)
  38. return false;
  39. i = x - 1;
  40. j = y - 1;
  41. while((i>=0)&&(j>=0))
  42. if(chessboard[i--][j--]==1) return false;
  43. i = x - 1;
  44. j = y + 1;
  45. while((i>=0)&&(j<N))
  46. if(chessboard[i--][j++]==1) return false;
  47. return true;
  48. }
  49. }
Add Comment
Please, Sign In to add comment