Advertisement
Guest User

Untitled

a guest
Aug 27th, 2014
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. package queens;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class Queens {
  6.  
  7. static int[] queens;
  8. int row = 0;
  9.  
  10. public Queens() {
  11. Scanner scan = new Scanner(System.in);
  12. System.out.println("Please Enter A Number");
  13. //int x = scan.nextInt();
  14. queens = new int[4];
  15.  
  16. }
  17.  
  18. boolean safe(int col) {
  19. int current = queens[col];
  20. for (int i = 1; i <= row; i++) {
  21. int pre = queens[col - i];
  22. if (pre == current
  23. || pre == current - i
  24. || pre == current + i) {
  25. return false;
  26. }
  27. }
  28. return true;
  29. }
  30.  
  31. public void placeQueens(int row) {
  32. for (int col = 0; col < queens.length; col++) {
  33. if (safe(col)) {
  34. queens[row] = col;
  35. if (row == queens.length - 1) {
  36. printOut();
  37. } else {
  38. row++;
  39. placeQueens(row);
  40. }
  41.  
  42. }
  43. }
  44. }
  45.  
  46. public void printOut() {
  47.  
  48. for (int i = 0; i < queens.length; i++) {
  49.  
  50. for (int j = 0; j < queens.length; j++) {
  51. if (queens[i] == j) {
  52. System.out.print("Q");
  53. } else {
  54. System.out.print("*");
  55. }
  56. }
  57. System.out.println("");
  58. }
  59. System.out.println("");
  60. }
  61.  
  62. public static void main(String[] args) {
  63. Queens q = new Queens();
  64. q.placeQueens(0);
  65. //q.printOut();
  66. }
  67.  
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement