Java LeetCode 51. N Queen

The n queen problem studies how to place n queens on an n×n chessboard and make the queens unable to attack each other.

Insert picture description here

The picture above shows a solution to the 8 Queens problem.
Given an integer n, return solutions to all different n queen problems.
Each solution includes a clear pawn placement plan for the n-queen problem, in which'Q' and'.' represent the queen and the empty position, respectively.

Backtracking algorithm

Very good solution and animation are here

class Solution {
    
    
    public List<List<String>> solveNQueens(int n) {
    
    
        List<List<String>> res = new ArrayList();
        Set<Integer> lie = new HashSet();
        Set<Integer> pie = new HashSet();
        Set<Integer> na = new HashSet();
        int nums[] = new int[n];
        Arrays.fill(nums,-1);
        back(n,0,lie,pie,na,nums,res);
        return res;
    }
    public void back(int n,int row,Set<Integer> lie,Set<Integer> na,Set<Integer> pie,int nums[],List<List<String>> res){
    
    
        if(row==n){
    
    
            List<String> result = genResult(nums,n);
            res.add(result);
            return;
        }

        for(int i=0;i<n;i++){
    
    
            if(lie.contains(i)){
    
    
                continue;
            }
            int pies = row+i;
            if(pie.contains(pies)){
    
    
                continue;
            }
            int nas = row-i;
            if(na.contains(nas)){
    
    
                continue;
            }

            nums[row]=i;
            lie.add(i);
            pie.add(pies);
            na.add(nas);

            back(n,row+1,lie,na,pie,nums,res);

            nums[row]=-1;
            lie.remove(i);
            pie.remove(pies);
            na.remove(nas);

        }
    }

    public List<String> genResult(int[] queens,int n) {
    
     
        List<String> tempResult = new ArrayList(); 
        for (int i=0;i<queens.length;i++) {
    
     
            char[] row = new char[n]; 
            Arrays.fill(row,'.'); 
            row[queens[i]] = 'Q'; 
            tempResult.add(new String(row)); 
            }
            return tempResult; 
            }

}

Guess you like

Origin blog.csdn.net/sakura_wmh/article/details/110847018