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

    import java.util.*;
    import java.io.*;
    import java.math.*;
    public class Hello
    {
        static int cnt =1;
         public static void main(String[] args) throws IOException
        {
            int n = 8;
            char[][] board = new char[n][n];
            for(int i=0;i<n;i++){
                for(int j=0;j<n;j++){
                        board[i][j] = '.';
                }
    
            }
            List<List<String>> res = new ArrayList<List<String>>();
            dfs(board,0,res);
    
            for (List<String > l:res) {
                for(String s:l)
                    System.out.println(s);
                System.out.println(cnt);
                cnt++;
            }
    
            //System.out.println(res);
        }
        private static void dfs(char[][] board, int colIndex, List<List<String>> res){
            if(colIndex == board.length){
                res.add(construct(board)); return;
            }
            for(int i=0;i<board.length;i++){
                if(validate(board,i,colIndex)){
                    board[i][colIndex] = 'Q';
                    dfs(board,colIndex+1,res);
                    board[i][colIndex] = '.';
                }
            }
    
        }
    
        private  static  boolean validate(char[][] board,int x,int y){
            for(int i=0;i<board.length;i++){
                for(int j=0;j<y;j++){
                    if(board[i][j] == 'Q' && ( x+y ==i+j || x-y == i-j || x==i )){
                        return false;
                    }
                }
            }
            return true;
        }
    
        public static List<String> construct(char[][] board){
            List<String> res = new LinkedList<String>();
            for(int i=0;i<board.length;i++){
                String s = new String(board[i]);
                res.add(s);
            }
            return res;
        }
    
    
    
    
    }
  • 相关阅读:
    POJ 最小球覆盖 模拟退火
    POJ 1379 模拟退火
    PythonTip(2)
    PythonTip(1)
    LA 3353 最优巴士线路设计
    LA 4254 贪心
    判断分析
    因子分析——因子得分
    因子分析——应用
    因子分析——因子旋转
  • 原文地址:https://www.cnblogs.com/vector11248/p/8042487.html
Copyright © 2011-2022 走看看