n queens problem -- p52 -- backtracking

Use a one-dimensional array (size n) queen[n] to represent the position of the queen in each row, so as to ensure that there is only one queen in each row

Then keep trying to see if you can put the queen, if you can put it, go to the next line, if you can't put it, try the next position

package Array;

import java.util.Map;

/**
 * The n-queens problem is the study of how to place n queens on an n×n chessboard in such a way that the queens cannot attack each other.

 The figure above shows a solution to the 8 queens problem.

 Given an integer n, return the number of distinct solutions for n queens.

 Example:

 Input: 4
 Output: 2
 Explanation: There are two different solutions to the 4 queens problem as follows.
 [
 [".Q..", // Solution 1
 "...Q",
 "Q...",
 "..Q."],

 ["..Q.", // Solution 2
 "Q...",
 "...Q",
 ".Q.."]
 ]


 */
public class p52 {
    private int result=0;
    public int totalNQueens(int n) {
        if(n==0||n==2||n==3)return 0;
        if(n==1)return 1;
        int queen[]=new int[n];
        for(int i=0;i<n;i++)queen[i]=-1;        //初始化为-1
        backTracking(0,n,queen);
        return result;
    }

    private  void backTracking( int i, int n, int queen[]){
         if (i==n){    // Get a solution 
            result++ ;
             return ;
        };
        for(int j=0;j<n;j++){
            queen[i] =j; // put the queen 
            if (!checkQueen(i,queen)){    // if it can't be put, try the next position 
                queen[i]=-1 ;
                 continue ;
            }else{
                backTracking(i +1,n,queen);        // Seek the position of the queen in the next line 
            }
        }
    }

    /**
     *
     * @param i line i
     * @param queen
     * @return   can be put and return true, cannot be put and return false
      */ 
    private  boolean checkQueen( int i, int queen[]){
         for ( int k=0;k<i;k++){        // Only check this line and in The position of the line before it 
            if (queen[i]==queen[k]||Math.abs(queen[i]-queen[k])-Math.abs(ik)==0){    // Not the same slash 
                return  false ;
            }
        }
        return true;
    }

    public static void main(String argv[]){
        p52 temp=new p52();
        System.out.println(temp.totalNQueens(4));
    }

}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325228235&siteId=291194637