Advertisement
Guest User

Untitled

a guest
Feb 19th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. public class Solution {
  2. private int res=0;
  3. public int totalNQueens(int n) {
  4.  
  5. int[][] board = new int[n][n];
  6. helper(board,0);
  7.  
  8. return res;
  9. }
  10. public void helper(int[][] board, int colIndex){
  11.  
  12. if(colIndex==board.length){
  13. res++;
  14. return;
  15. }
  16.  
  17. for(int i=0;i<board.length;i++){
  18. if(validate(board, i, colIndex)){
  19. board[i][colIndex] = 1;
  20. helper(board, colIndex+1);
  21. board[i][colIndex] = 0;
  22. }
  23. }
  24. }
  25. public boolean validate(int[][] board, int x, int y){
  26.  
  27. for(int i=0;i<board.length;i++){
  28. for(int j=0;j<y;j++){
  29. if(board[i][j]==1 && (x + j == y + i || x + y == i + j || x == i)){
  30. return false;
  31. }
  32. }
  33. }
  34. return true;
  35. }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement