My easy understand solution using dfs


  • -1
    D
    public class Solution {
    public List<List<String>> solveNQueens(int n) {
    	List<List<String>> list=new ArrayList<List<String>>();
            helper(list,new ArrayList<Integer>(),0,n);
            return list;
        }
     private void helper(List<List<String>> list,List<Integer> ways,int level,int n){
    	 if(level<=n-1){
    	 
    	 for(int row=0;row<n;row++){
    		if(!is(ways,level,row)) continue;
    		 ways.add(row);
    		if(level==n-1){
    			List<String> s=new ArrayList<String>();
    			for(int i:ways){
    				String tmp="";
    				int j=0;
    				while(j<n){
    					if(j==i) tmp+="Q";
    					else tmp+=".";
    					j++;
    				}
    			s.add(tmp);
    			}
    			list.add(s);
    			ways.remove(ways.size()-1);
    			return;
    		}
    		 helper(list,ways,level+1,n);
    		 ways.remove(ways.size()-1);
    	 }
    	 }
    	 return;
     }
    private boolean is(List<Integer> list,int level,int row){
    	if(list.contains(row)) return false;
    	for(int i=0;i<list.size();i++){
    		if(Math.abs(row-list.get(i))==level-i){
    			return false;
    		}
    	}
    	return true;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.