scala 解决8皇后问题

10、Prolog与Scala:两种编程语言的深入剖析 本文深入剖析了两种编程语言Prolog和Scala的特点及其应用场景。Prolog是一种以逻辑编程为核心的语言,适用于自然语言处理、游戏开发、人工智能等领域;而Scala是一种结合面向对象和函数式编程的混合语言,特别适合并发编程和企业级开发。文章通过对比两者的优缺点,提供了选择合适语言的决策流程,并给出了实践建议和未来展望。 阅读详情
val n = 14
val Col = new Array[Boolean](n)
val Bevel1 = new Array[Boolean](n*2)
val Bevel2 = new Array[Boolean](n*2)
def col(y: Int) = !Col(y)
def bevel1(x: Int, y: Int) = !Bevel1(x-y+n-1)
def bevel2(x: Int, y: Int) = !Bevel2(x+y)
def dfs(x: Int): Int = if(x == n) 1 else Range(0, n).foldLeft(0)((a, b) => a + solve(x, b))
def solve(x: Int, i: Int): Int = {
    if(col(i) && bevel2(x, i) && bevel1(x, i)){
        Col(i) = true; Bevel1(x-i+n-1) = true; Bevel2(x+i) = true
        val ans = dfs(x+1)
        Col(i) = false; Bevel1(x-i+n-1) = false; Bevel2(x+i) = false
        ans
    }else 0
}
println("The number of queue is: " + n + " " + "result: " + dfs(0))

这个代码解决15后大约需要半分钟,16后3分钟

思路: 回溯。当走到某个地方后,先判断这个地方能不能走,就是判断该位置所在的行,列,斜是否有皇后。以为是一行一行往下走,该行上肯定没有皇后

OpenCV C++ 图像处理实战 ——《基于轮廓比对的缺陷检测》 本文使用OpenCV C++ 实现基于轮廓比对的缺陷检测。 阅读详情

相关推荐

RLHF的数学表示

RLHF(Reinforcement Learning with Human Feedback)是一种结合了强化学习和人类反馈的机器学习方法。它通常用于训练智能体(agent)在复杂环境中做出决策,同时利用人类的反馈来指导和改进学习过程。RLHF 没有一个统一的数学表示式,因为它依赖于具体的应用场景和实现细节。然而,我们可以从强化学习和人类反馈的角度来描述RLHF的一些关键数学概念。

xw555666的博客 689

八皇后问题的Scala解法

  好久没做过算法题了,那本《算法导论》都堆了N cm的一层灰了-_-   废话不多说了,下面是代码: [code="java"]/** &# Queen.scala 八皇后问题的Scala解法 @author Eastsun @date 2008.5.19 */ object Queen extends Application{ solve(...

JavaSxy的专栏 279

nature子刊:MCNN基于电池故障诊断的模型约束的深度学习方法

本研究提出了一种基于模型约束神经网络(MCNN)的锂离子电池在线故障诊断方法,整合物理模型与深度学习,有效解决了随机工况下传统方法诊断精度低、依赖故障样本等问题。通过统计修正电池包模型和双向LSTM网络,实现了电池状态的高精度预测(平均RMSE 3.9%),并设计模型耦合自动编码器提取可解释特征。在包含18.2百万条真实车辆数据的验证中,该方法故障检测TPR在FPR=0.1时达85%,较基准方法提升超46.5%,且能提前30分钟预警内部短路等故障。研究还展示了算法在跨电池包结构迁移中的优越性,为工业应用提供

hasakie的博客 1759

scala 回溯法解决八皇后问题

object EightQueen extends App{ val queenArray = new Array[Int](8) var num = 0 def printqueen(){ for(i <- 0.until(8);j <- 0.until(8)){ if(j == queenArray(i)) print('*') else print('-') if(j

o1101574955的专栏 1093

Spring Authorization Server自定义密码模式:突破标准OAuth2限制,实现MFA与复杂业务集成

OAuth 2.0授权框架是构建现代应用安全体系的基石,其密码模式(Resource Owner Password Credentials Grant)提供了一种直接的资源所有者凭证交换令牌的机制。该模式的核心原理是客户端收集用户密码并直接向授权服务器请求访问令牌,适用于受信任的客户端场景。在技术价值上,它简化了某些传统应用的OAuth集成流程。然而,标准实现往往难以满足复杂的现实业务需求,例如需要集成多因素认证(MFA)、对接外部LDAP目录服务或执行自定义密码加密校验等场景。Spring Authori

weixin_34302561的博客 438

【Bug已解决】Claude Desktop Cowork 报错 Workspace unavailable 解决方案

方案适用场景推荐指数确认虚拟机镜像下载完整性排查的第一步,最基础的前提检查⭐⭐⭐⭐⭐确认虚拟机平台功能已启用Windows 系统功能层面的必要条件⭐⭐⭐⭐⭐重启 CoworkVMService快速尝试恢复服务正常状态⭐⭐⭐⭐完全重启客户端排除临时性状态错乱⭐⭐⭐⭐降级使用文件工具临时替代方案,不阻塞当前工作⭐⭐⭐报错的本质是Cowork 功能依赖的虚拟机管理服务,在 Windows 应用包隔离机制下未能正确定位虚拟机文件的实际存放路径。

博客 6240

scala解决八皇后问题

八皇后问题,是一个古老而著名的问题,是回溯算法的典型案例。        该问题是国际西洋棋棋手马克斯·贝瑟尔于1848年提出:               在8×8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,               问有多少种摆法? def nqueens(n:Int):Set[List[Int]] ={

shuangshaung_的博客 542

YOLO格式数据集【数据增强】终极脚本 | 70+种顶级数据增强方法 | 可带标签增强

YOLO格式数据集【数据增强】终极脚本 | 70+种顶级数据增强方法 | 可带标签增强

Coding... 5503

scala 深搜法解决八皇后问题

object EightQueen2 extends App{ val pos = new Array[Int](8) val rowvisited = new Array[Boolean](8) val colvisited = new Array[Boolean](8) val maindiagonalvisited = new Array[Boolean](15) val coun

o1101574955的专栏 912

《Python等级认证CCF-GESP真题解析》专栏总目录

❤️ 专栏名称:《🌸 专栏介绍:中国计算机学会GESP《CCF编程能力等级谁》Python编程(1~8级)历届真题解析。🚀 订阅专栏:订阅后可阅读专栏内所有真题解析,真题持续更新中,限时9.9元,欢迎订阅!

人生就是一个不断学习的过程 1885

快速生成2D卡通人物的AI工具:开启Live2D角色创作的新时代

随着这一创新工具的推出,我们正见证着Live2D角色创作进入了一个全新的阶段。它不仅极大地简化了角色设计的过程,也为广大创作者提供了一种全新的表达方式。对于那些渴望将脑海中的构思迅速转化为现实的人来说,这无疑是一大福音。现在就访问项目主页,开始探索无限可能吧!t=O83A项目主页https://human3daigc.github.io/Textoon_webpage/

这里汇聚了前沿的技术分享与实用的开发技巧,带你探索从创意到企业的技术创业之路。 4839

使用回溯法解决八皇后问题(同样适用于N皇后)。

在学习数据结构的时候,看到了一道八皇后的问题。写完后,再去网上查看发现原来这个问题有这么多的优化解法,相比之下相形见绌。但我还是记录下来,有兴趣的小伙伴可以看看。 先大致说下我的思路 创建一个初始化值为0的8x8的数组,0代表无皇后且不在其他皇后的攻击范围,-1代表皇后的位置,&amp;amp;amp;amp;amp;amp;amp;gt;0的整数代表格子在皇后的攻击范围。例如某个格子的数字为3说明该格子在3个皇后的攻击范围。 下面是代码,最后求...

Twilight blog 1034

沙猫群优化算法(SCSO)详解:从沙漠生存智慧到全局优化引擎

本文详细介绍了沙猫群优化算法(SCSO),这是一种新型元启发式优化算法,灵感来源于沙猫在沙漠环境中的卓越狩猎行为。SCSO通过模拟沙猫的低频探测能力和精确攻击策略,将优化问题转化为搜索和捕获"猎物"的过程。算法核心包括探索阶段(全局搜索)和开发阶段(局部精细搜索),通过灵敏度范围模型和自适应控制参数实现两者的平衡。SCSO具有参数简单、收敛性能好等优点,适用于解决复杂全局优化问题。

qq_42212808的博客 202

八皇后问题

八皇后问题,是一个古老而著名的问题,是回溯算法的典型案例。该问题是国际西洋棋棋手马克斯·贝瑟尔于1848年提出:在8×8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法。 scala解法 def nqueen(n:Int) : Set[List[Int]] ={   def placeQueen(k:Int) :Set

abc_321a的博客 397

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

N皇后不互吃问题的scala实现

基本介绍:   国际象棋是8*8的棋盘,每个位置可以放置一个棋子。国际象棋中的皇后棋子,可以向横、向竖、向斜行走,并吃掉路线上的其他棋子 N皇后不互吃问题,为:在N * N 的棋盘上,放置N个皇后棋子;其中任意两个皇后彼此不会互吃。找出所有可能的位置集合 思路: 因为皇后能横竖斜吃子的设定,所以存在一个基本条件:要在N * N的棋盘上放置N个皇后不互吃,那么每一行有且只有一个皇后。 所...

成长之路 340

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

大数据技术之_16_Scala学习_13_Scala语言的数据结构和算法_Scala学习之旅收官之作

大数据技术之_16_Scala学习_13

黑泽君 685

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

N皇后问题的遗传算法Python工程实现与调优

遗传算法(GA)是一种基于自然选择与进化机制的全局优化方法,其核心在于编码设计、适应度函数构建与种群演化策略。在高维约束满足问题中,如N皇后问题,GA的价值随规模增大而凸显——当N≥20时,暴力搜索失效,而合理设计的GA可通过变异驱动、精英选择与适应度塑形,在稀疏解空间中稳定收敛。本文聚焦GA的工程落地:采用行-列整数编码规避非法解生成,以1/(q+0.001)构造具备悬崖式选择压力的fitness函数,并通过种群规模、染色体长度与迭代代数的‘铁三角’参数协同,支撑N=100规模下的可复现求解。适用于智能优

cuyi7076的博客 392

默写八皇后

在看Scala视频时,有个例子说是用Scala写八皇后,我突然想我现在能不能马上写出八皇后呢? 于是打开IDE开始练习 共计20分钟不到 其中有十分钟是在写如何判断某一点上能否放一个皇后(横竖斜) 这个速度还算是可以 #include #include #include "string" #include "iostream" #include "fstream" #in

编码之路 957

函数式编程笔记 11

Set Set是另一种集合,和序列写法相似: val fruit = Set("apple", "banana", "pear") val s = (1 to 6).toSet 复制代码 大部分序列上的操作在Set上也能用: s map (_ + 2) fruit filter (_.startWith == "app") s.nonEmpty 复制代码Set和序列的区别是Set中不包含相同元素。...

weixin_33807284的博客 94

python的异常处理都能用if语句来替代_Python对异常与错误的处理策略,用try...except,还是if...else...,哪种比较好?...

Beginning Python From Novice to Professional, 2nd Edition, CHAPTER 8, EXCEPTIONS, Page 173:正文中这样描写:The point is that using try/except statements is in many cases much more natural (more “Pythonic”) th...

weixin_42500477的博客 630

python的异常处理都能用if语句来替代_Python 对异常与错误的处理策略,用 try...except,还是 if...else...,哪种比较好?...

Beginning Python From Novice to Professional, 2nd Edition, CHAPTER 8, EXCEPTIONS, Page 173:正文中这样描写:The point is that using try/except statements is in many cases much more natural (more “Pythonic”) th...

weixin_39915505的博客 388

七周七语言:理解多种编程范型pdf

下载地址:网盘下载作者简介······作者简介:Bruce A. Tate RapidRed公司总裁,该公司主要为Ruby轻量级开发提供咨询。他曾任职于IBM公司,并担任过多家公司的客户解决方案总监和CTO。著作有十余本,包括荣获Jolt大奖的Better, Faster, Lighter Java。译者简介:戴玮 80后宅男,中科院自动化所在读...

weixin_30788619的博客 452

递归函数总结

本文系统讲解了递归的概念、形态与优化方法。递归是函数调用自身的过程,具有两个核心特征:自我调用和终止条件。递归可分为线性递归(头递归/尾递归)和树形递归,不同形态在调用结构和执行流程上存在差异。文章通过时序图和调用树对比了头递归与尾递归的差异,解释了编译器为何只能优化尾递归。针对递归的性能问题,提出了三种优化方向:分而治之、动态规划/记忆化、DFS/BFS转换。重点分析了记忆化(缓存中间结果)和动态规划(自底向上求解)的原理,并以零钱兑换问题为例展示了动态规划的实现方法。文章指出朴素递归时间复杂度通常为指数

你的指尖有改变世界的力量 346

七周七语言:理解多种编程范型(2011年Jolt大奖图书)

七周七语言:理解多种编程范型(2011年Jolt大奖图书)       编辑推荐   2011年Jolt大奖图书  带你轻松入门七种先锋语言  开阔视野,享受更多编程乐趣         基本信息 原书名:Seven Languages in Seven Weeks: A Pragmatic Guide to Learning Programming Languages ...

china-pub网上书店 285

四皇后问题

#include #include #define N 5// using namespace std; void Print(int n, int array[]){ for (int j = 1; j <= n; j++) cout<<array[j]<<" "; //输出最终的棋盘布局,每个数组元素值表示各行棋盘所在的该列放置皇后 cout<<endl<<endl; } bool is

fishorbird的博客 1467
上一篇: 新的开始
下一篇: scala 快速排序与合并排序
badopencoder
博客等级 码龄10年 0粉丝 7原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值