zoukankan      html  css  js  c++  java
  • N皇后问题

    class Solution {
    /**
    * Get all distinct N-Queen solutions
    * @param n: The number of queens
    * @return: All distinct solutions
    * For example, A string '...Q' shows a queen on forth position
    */
    ArrayList<ArrayList> solveNQueens(int n) {
    // write your code here
    ArrayList path = new ArrayList();
    ArrayList<ArrayList> result = new ArrayList<ArrayList>();
    if( n<0 )
    return result;
    int cols[] = new int[n];
    DFS_helper(n,result,0,cols);
    return result;

    }
    public void DFS_helper(int nQueens,ArrayList<ArrayList<String>> result,int row,int[] cols){
        if(row == nQueens ){
            ArrayList<String> path = new ArrayList<String>();
            for(int i = 0;i<nQueens ;i++){
                String s = "";
                for(int j = 0;j< nQueens ;j++){
                    if(j == cols[i])
                        s = s + "Q";
                    else
                        s = s + ".";
                }
                path.add(s);
    
            }
            result.add(path);
        }else{
            for(int i = 0;i<nQueens ;i++){
                cols[row] = i;
                if(isValid(row,cols))
                    DFS_helper(nQueens,result,row + 1 ,cols);
            }
        }
    }
    public boolean isValid(int row ,int[] cols){
        for(int i=0;i<row;i++){
            if(cols[row] == cols[i] || Math.abs(cols[row] - cols[i]) == row - i)
            return false;
        }
        return true;
    }
    

    };

  • 相关阅读:
    元组类型内置方法
    python的两种编程模式
    Python和Python解释器
    异常处理
    文件的三种打开方式
    python解释器的安装
    编程语言的分类
    计算机基础之编程
    linux 安装postgresql
    CentOS7 部署 gitlab
  • 原文地址:https://www.cnblogs.com/yiwenhao/p/7407546.html
Copyright © 2011-2022 走看看