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;
        }
  • 相关阅读:
    C语言 · 新生舞会
    C语言 · 集合运算
    C语言 · 字符串的展开
    C语言 · 学做菜
    C语言 · 最长公共子序列 · 最长字符序列
    C语言 · 复数求和
    C语言 · 扶老奶奶过街
    C语言 · 删除重复元素
    1-3
    1-4
  • 原文地址:https://www.cnblogs.com/Antech/p/3779167.html
Copyright © 2011-2022 走看看