zoukankan      html  css  js  c++  java
  • N-Queens_review()

    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:

        这次用了一维数组,横坐标为下表,纵坐标为值

    public class Solution {
        public List<String[]> solveNQueens(int n) {
          ArrayList<String[]> res= new ArrayList<String[]>();
            int nrow= n;
            int[] nQueen= new int[n];
            DFS_nQueen(res,0,nrow,nQueen);
            return res;
        }
        public void DFS_nQueen(ArrayList<String[]> res, int row, int nrow,
                int[] nQueen) {
            // TODO Auto-generated method stub
            if(row==nrow){
                String[] unit=new String[nrow];
                for(int i=0;i<nrow;i++){
                    StringBuilder s=new StringBuilder();
                    for(int j=0;j<nrow;j++){
                        if(j==nQueen[i]){
                            s.append("Q");
                        }else{
                            s.append(".");
                        }
                    }
                    unit[i]=s.toString();
                }
                res.add(unit);
            }else{
                for(int i=0;i<nrow;i++){
                    nQueen[row]=i;
                if(isValid(nQueen,row)){
                    DFS_nQueen(res,row+1,nrow,nQueen);    
                }
                }
            }
        }
        public boolean isValid(int[] array,int row){
            for(int i=0;i<row;i++){
                if(array[i]==array[row] || (Math.abs(i-row)==Math.abs(array[i]-array[row]))){
                    return false;
                }        
            }
            return true;
        }  
        
    }
  • 相关阅读:
    文件共享服务之FTP
    通过rsycn实现数据同步
    rsync命令的使用
    Linux之ssh服务
    跳板机的工作原理和简单的跳板机实现
    Linux进程管理
    javaweb图片上传 tomcat重新部署 图片消失
    KindEditor 上传文件
    PL/SQL通过修改配置文件的方式实现数据库的连接
    PermGen space
  • 原文地址:https://www.cnblogs.com/joannacode/p/4548190.html
Copyright © 2011-2022 走看看