Advertisement
Guest User

Untitled

a guest
Dec 10th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.65 KB | None | 0 0
  1. package queens_8;
  2.  
  3. public class board {
  4.  
  5. private static int board[][];
  6. private int numQueens;
  7.  
  8. public board() {//default constructor
  9. numQueens = 0;
  10. board = new int[8][8];
  11. for (int i = 0; i < 8; i++) {
  12. for (int j = 0; j < 8; j++) {
  13. board[i][j] = 0;
  14. }
  15. }
  16. }
  17.  
  18. public int getnumQueens() {
  19. return numQueens;
  20. }
  21.  
  22. public void start() {
  23.  
  24. solve(0);
  25.  
  26. }
  27.  
  28. public boolean solve(int numQueens) {
  29.  
  30. if (numQueens == 8) {
  31. System.out.println("DONE");
  32. this.display();
  33. return true;
  34. } else {
  35. for (int i = 0; i < 8; i++) {
  36. for (int j = 0; j < 8; j++) {
  37. if (isvalidMove(i, j) == 0) {
  38. this.placeQueen(i, j, 0);
  39. numQueens++;
  40. if (solve(numQueens)) {
  41. return true;
  42. } else {
  43. this.placeQueen(i, j, 1);
  44. numQueens--;
  45. }
  46. }
  47. }
  48. }
  49. }
  50. return false;
  51. }
  52.  
  53. public static int isvalidMove(int x, int y) {
  54. for (int i = 0; i < 8; i++) {
  55. if (get(x, i) == 1) {
  56.  
  57. return -1;
  58. }
  59. if (get(i, y) == 1) {
  60. return -1;
  61. }
  62. }
  63.  
  64. // check diag
  65. for (int j = 0; j < 8; j++) {
  66. if (get(x - j, y - j) == 1) {
  67. return -1;
  68. }
  69. if (get(x - j, y + j) == 1) {
  70. return -1;
  71. }
  72. if (get(x + j, y - j) == 1) {
  73. return -1;
  74. }
  75. if (get(x + j, y + j) == 1) {
  76. return -1;
  77. }
  78.  
  79. }
  80. return 0;
  81. }
  82.  
  83. public int placeQueen(int x, int y, int type) {
  84.  
  85. if (type == 0) {
  86. board[x][y] = 1;
  87. numQueens++;
  88. return 0;
  89. } else if (type == 1) {
  90. board[x][y] = 0;
  91. return 0;
  92.  
  93. }
  94. System.err.println("Wrong type");
  95. return -3;
  96. }
  97.  
  98. public static int get(int x, int y) {
  99.  
  100. if (x < 0 || y < 0 || x > 7 || y > 7) {
  101. return -1;
  102. }
  103.  
  104. return board[x][y];
  105. }
  106.  
  107. public void display() {
  108. for (int i = 0; i < 8; i++) {
  109. for (int j = 0; j < 8; j++) {
  110. System.out.print(this.get(i, j) + " ");
  111. }
  112. System.out.println("");
  113. }
  114. }
  115. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement