首页 > 代码库 > [leetcode]N-Queens

[leetcode]N-Queens

问题描述:

The n-queens puzzle is the problem of placingn queens on an n×n chessboard such that no two queens attack each other.

技术分享

Given an integer n, return all distinct solutions to then-queens puzzle.

Each solution contains a distinct board configuration of then-queens‘ placement, where ‘Q‘ and ‘.‘ both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

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

基本思想:

回溯法。

代码:


    public void generateSolution(int [] record,int n, List<String []> result){  //Java
	        
	        String [] solution = new String[n];
	        for(int i =0; i < n; i++){
	            String row = "";
	            for(int j = 0; j < n; j++){
	                if(record[i]-1 == j)
	                    row += "Q";
	                else row +=".";
	            }
	            solution[i] = row;
	        }
	        result.add(solution);
	    }
	    public boolean check_pos(int index, int loop, int [] record){

            for(int i = 0; i < index; i++){
                if(record[i] == loop)
                    return false ;
                if(record[i]+i == index + loop)
                	return false ;
                if(record[i] -loop == i - index )
                	return false ;
            }  
	        return true;
	    }
	    
	    public void  subNQueen(int [] record,int index, List<String[]> result, int n){
	    	if(index == n){
	    		generateSolution(record, n,result);
	    	}
	    	
		    for(int loop = 1; loop <=n; loop++){
		    	if(check_pos(index, loop, record)){
		    		record[index] = loop;
			        subNQueen(record,index+1,result,n);
			        record[index] = 0;
		    	}
		    }
	    
	    }
	    public List<String[]> solveNQueens(int n) {
	    
	    	int index = 0;
	        int [] record = new int[n];
	        List<String [] > result = new ArrayList<String []>();   
	        subNQueen(record,0,result,n);
	        return result;
	    }

[leetcode]N-Queens