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;
    }
    

    };

  • 相关阅读:
    斐波那契数列的递归和非递归实现
    二叉树遍历
    基础总结
    内部类
    I/O dempo
    读取文件注意事项
    eclipse 主题设置
    String 常用函数
    多态的理解
    ffmpeg处理RTMP流媒体的命令大全
  • 原文地址:https://www.cnblogs.com/yiwenhao/p/7407546.html
Copyright © 2011-2022 走看看