Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2014
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class NQueens {
  4. static int n;
  5. int[][] board = new int[n][n];
  6. public static void main(String[] args) {
  7.  
  8. //int result;
  9. int col = 0;
  10. Scanner input=new Scanner(System.in);
  11. n=input.nextInt();
  12. if(n < 4)
  13. System.out.println("the result is 0");
  14. else
  15. count(0);
  16.  
  17. }
  18.  
  19. int cnt=0;
  20. void count(int col){
  21. if(col == n){
  22. cnt++;
  23. System.out.println("the result is " + cnt);
  24. }
  25.  
  26. else{
  27. for(int row=0 ; row<n ; row++){
  28. if(placeQueen(row, col))
  29. count(col+1);
  30. else
  31. removeQueen(row , col);
  32. }
  33. }
  34.  
  35. }
  36.  
  37. boolean placeQueen(int row , int col){
  38. boolean x =false;
  39. if(validPlace(row , col)){
  40. setQueen(row , col);
  41. x = true;
  42. }
  43. return x;
  44. }
  45. boolean validPlace(int row ,int col){
  46. boolean x = false;
  47. if(board[row][col] != -1)
  48. x=true;
  49. return x;
  50. }
  51. void setQueen(int row , int col){
  52. board[row][col] = 1;
  53. killCell(row , col);
  54. }
  55. void killCell(int row , int col){
  56. for(int i=col+1 ; i<n ; i++)
  57. board[row][i] = -1;
  58. for(int k=col+1 ; k<n ; k++){
  59. for(int j=0 ; j<n ; j++)
  60. if(Math.abs(row-j) == Math.abs(col-k))
  61. board[j][k] = -1;
  62. }
  63. }
  64. void removeQueen(int row , int col ){
  65. board[row][col] = 0;
  66. refreshCell(row , col);
  67. }
  68. void refreshCell(int row , int col){
  69. for(int i =col+1 ; i<n ; i++)
  70. board[row][i]=0;
  71. for(int k=col+1 ; k<n ; k++){
  72. for(int j=0 ; j<n ; j++)
  73. if(Math.abs(row-j) == Math.abs(col-k))
  74. board[j][k]=0;
  75. }
  76. }
  77.  
  78. public static void main(String[] args) {
  79.  
  80. //int result;
  81. int col = 0;
  82. Scanner input=new Scanner(System.in);
  83. n=input.nextInt();
  84. if(n < 4)
  85. System.out.println("the result is 0");
  86. else {
  87. NQueens nq = new NQueens();
  88. nq.count(n);
  89. }
  90.  
  91. }
  92.  
  93. public void NQueens(int starting_n) {
  94. start = starting_n;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement