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

    Write an algorithm to print all ways of arranging eight queens on an 8*8 chess board so that none of them share the same row, column or diagonal.

    思路:

    本质上是DFS, 从第一行开始一行行地放棋子,每次放棋子之前根据当前的棋盘检查一下约束。

    Code (from book):

        void placeQueen(int row, Integer[] columns, ArrayList<Integer[]> result){
            if(row == GRID_SIZE){
                result.add(columns.clone());
                return;
            }
            
            for(int col = 0; col < GRID_SIZE; ++col){
                if(checkValid(row, col, columns)){
                    columns[row] = col;
                    placeQueen(row + 1, columns, result);
                }
            }
        }
        
        // No need to check the same row because the program
        // proceeds one row at a time
        boolean checkValid(int row, int column, Integer[] columns){
            for(int i = 0; i < row; ++i){
                int j = columns[i];
                
                // check the same column
                if(column == j){
                    return false;
                }
                
                // check same diagonal
                if(Math.abs(row - i) == Math.abs(column - j)){
                    return false;
                }
            }
            return true;
        }
  • 相关阅读:
    逆变和协变
    委托的泛型版本
    委托的协变和逆变
    IIS8应用池重启脚本
    JS获取url参数及url编码、解码
    Jmeter压测Thrift服务接口
    浏览器插件及好用的小工具
    Jmeter入门实例
    BugBash活动分享
    如何作缺陷分析
  • 原文地址:https://www.cnblogs.com/Antech/p/3779167.html
Copyright © 2011-2022 走看看