zoukankan      html  css  js  c++  java
  • leetcode--N-Queens

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

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

    Each solution contains a distinct board configuration of the n-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.."]
    ]


    dfs method.
    public class Solution {
        public List<String[]> solveNQueens(int n) {
           List<String[]> placement = new ArrayList<String[]>();
    		if(n == 1){
    			placement.add(new String[]{"Q"});
    	        return placement;
    	    }
    		if(n >= 4){
    			List<Integer> position = new ArrayList<Integer>();
    			dfs(n, 0, position, placement);
    		}
    		return placement;	
    	}
    		
    	private boolean dfs(int n, int row, List<Integer> position, List<String[]> placement){
    		if(row == n) return true; 
    		for(int i = 0; i < n; ++i) {
    			if(isValidPosition(row * n + i, position, n)){
    				position.add(row * n + i);
    				if(dfs(n, row + 1, position, placement))
    					generateSolution(position,placement, n);
    				position.remove(row);
    			}
    		}
    		return false;
    	}
    		
    	private boolean isValidPosition(int k, List<Integer> position, int n){
    		for(int i = 0; i < position.size(); ++i){
    			if( k % n == position.get(i) % n || Math.abs( k % n - position.get(i) % n) == k / n - i) 
    				return false;
    		}
    		return true;
    	}
    		
    	private void generateSolution(List<Integer> position, List<String[]> placement, int n){
    		char[] oneRow = new char[n];
    		for(int i = 0; i < n; ++i)
    			oneRow[i] = '.';
    		String[] oneSolution = new String[n];
    		for(int i = 0; i < n; ++i){
    			oneRow[position.get(i) % n] = 'Q';
    			oneSolution[i] = new String(oneRow);
    			oneRow[position.get(i) % n] = '.';
    		}
    		placement.add(oneSolution);     
        }
    }
    

      






  • 相关阅读:
    C语言程序设计习题参考答案
    C语言程序设计 数据类型转换
    C语言程序设计 练习题参考答案 第二章
    计算机等级考试二级C语言考试复习五要点
    计算机等级考试二级快速复习法
    C语言程序设计 辗转相除法
    ReportViewer (RDLC) 中的换行符是什么
    关于axis2中对soapfault的处理的一个小bug
    java多线程中利用优先级来分配CPU时间的实例
    马云演讲
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3825843.html
Copyright © 2011-2022 走看看