• 9.9---n皇后问题(CC150)


    思路:首先写一个检查能不能摆的函数。boolean checkValid(int[] columns,int row1, int column1);意思是row1行摆在column1列可不可以。

    然后是place函数。第一个参数row表示现在摆第几行。第一行可以摆n次位置,然后往下也是8ci。也就是相当于8^8次检查。如果能摆了,往下一行,如果不能摆往后移一列。当row>8说明摆好了。那么计数器+1.

    答案:

    public class Solution{
        
        public static void main(String[] args){
    
            System.out.println(nQueens(8));
        }
        public static int nQueens(int n) {
            // write code here
            int[] columns = new int[n];
            int[] a = new int[1];
            placeQueens(n,0,columns,a);
            return a[0];
        }
        public static void placeQueens(int n,int row, int[] columns,int[] a){
            if(row == n){
                a[0]++;
            }else{
                for(int col = 0; col < n; col++ ){
                    if(checkValid(columns,row,col)){
                        columns[row] = col;//放皇后
                        placeQueens(n,row + 1,columns,a);
                    }
                }
            }
        }
        
        
        public static boolean checkValid(int[] columns, int row1, int column1) {
            for (int row2 = 0; row2 < row1; row2++) {
                int column2 = columns[row2];
                if (column1 == column2) { 
                    return false;
                }
                int columnDistance = Math.abs(column2 - column1); 
                int rowDistance = row1 - row2; // row1 > row2, so no need to use absolute value
                if (columnDistance == rowDistance) {
                    return false;
                }
            }
            return true;
        }
    }
  • 相关阅读:
    innerHTML和innerText的使用和区别
    HTML5的快捷方式
    JSP相关知识
    <<,>>(有符号位移)和>>>(无符号位移)的使用方法,及差别
    JDK环境变量配置
    在table中加入<hr />标签为什么横线会跑到上边?
    有关List、Set、Map的基础了解
    菜鸟级-正则表达式
    Git常用的基本操作
    Mysql基本操作
  • 原文地址:https://www.cnblogs.com/yueyebigdata/p/5098045.html
Copyright © 2020-2023  润新知