八皇后

八皇后,N皇后及其变种问题 八皇后问题和N皇后问题 n-皇后问题是指将 n 个皇后放在 n∗n 的国际象棋棋盘上,使得皇后不能相互攻击到,即任意两个皇后都不能处于同一行、同一列或同一斜线上。 现在给定整数n,请你输出所有的满足条件的棋子摆法。 输入格式 共一行,包含整数n。 输出格式 每个解决方案占n行,每行输出一个长度为n的字符串,用来表示完整的棋盘状态。 其中”.”表示某一个位置的方格状态为空,”Q”表示某一个位置的方格上摆着皇后。 每个方案输出完成后,输出一个空行。 输出方案的顺序任意,只要不重复且没有遗漏即可。 数据范围 1 阅读详情

说明:西洋棋中的皇后可以直线前进,吃掉遇到的所有棋子,如果棋盘上有八个皇后,则这八个皇后如何相安无事的放置在棋盘上,1970年与1971年, E.W.Dijkstra与N.Wirth曾经用这个问题来讲解程式设计之技巧。

解法:关于棋盘的问题,都可以用递归求解,然而如何减少递归的次数?在八个皇后的问题中,不必要所有的格子都检查过,例如若某列检查过,该该列的其它格子就不用再检查了,这个方法称为分支修剪。

#include <stdio.h>

#include <stdlib.h>

#define N 8

 

int column[N+1]; // 同栏是否有皇后,1表示有

int rup[2*N+1]; // 右上至左下是否有皇后

int lup[2*N+1]; // 左上至右下是否有皇后

int queen[N+1] = {0};

int num; // 解答编号

void backtrack(int); // 递归求解

int main(void) {

    int i;

    num = 0;

    for(i = 1; i<= N; i++)

       column[i] = 1;

    for(i = 1; i<= 2*N; i++)

        rup[i] =lup[i] = 1;

   backtrack(1);

    return 0;

}

void showAnswer() {

    int x, y;

   printf("\n解答%d\n", ++num);

    for(y = 1; y <= N; y++) {

        for(x =1; x <= N; x++) {

           if(queen[y] == x) {

               printf(" Q");

            }

            else{

               printf(" .");

            }

        }

       printf("\n");

    }

}

void backtrack(int i) {

    int j;

    if(i > N){

       showAnswer();

    }

    else {

        for(j =1; j <= N; j++) {

           if(column[j] == 1 &&

                rup[i+j] == 1 && lup[i-j+N] == 1) {

               queen[i] = j;

               // 设定为占用

               column[j] = rup[i+j] = lup[i-j+N] = 0;

               backtrack(i+1);

               column[j] = rup[i+j] = lup[i-j+N] = 1;

            }

        }

    }

}
全排序vs八皇后问题vs三角八皇后 假设要求字符串/数组的全排序,例如:"123"的全排序,第1位有3种选择,第2位有2种选择,第3位1种选择,时间复杂度显然是3!.实际上容易知道,对于n个字符,全排序一共有n!种可能,是n!时间复杂度的.我们需要找一个算法求出所有的可能的排序,最好的办法是递归,如果选用循环,需要n层嵌套,不太现实.假设我们已经拥有一个函数 FullPermutation(A[n])能将数组A[n]全排序,于... 阅读详情

相关推荐

八皇后-go实现

八皇后游戏规则说明: 在8×8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法。(百度百科) 延申到n皇后,规则已知,算法的空间复杂度为O(n^2), 空间复杂度为O(n), package main import "fmt" //判断该位置是否满足八皇后规则 func eJudge(e []int, i int)...

qq_36557960的博客 335

深入浅出讲解八皇后&n皇后问题

深入浅出讲解八皇后和n皇后问题规则分析第一种方式:问题分析代码如下1.0代码如下1.1第二种方式:代码如下1.2代码如下1.3 这次朋友想看,有是事解释讲解部分下次细说 该文章会从简单的程序开始讲解,也会涉及到一些算法(递归、回溯)、数据结构等一些知识,最后的程序是我现在为止想到的最优算法,讲解过程就是问题思考的过程 规则分析 在8×8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都...

weixin_43884534的博客 1066

从PWM到正弦波:RC低通滤波器的魔法转换之旅

本文详细介绍了如何利用RC低通滤波器将STM32F103生成的PWM信号转换为高质量正弦波的技术原理与实践方法。通过分析滤波器设计、参数计算、硬件实现及Proteus仿真验证,为嵌入式开发者提供了一套完整的PWM转正弦波解决方案,适用于电机控制、音频信号生成等多种应用场景。

jupi8的博客 380

八皇后12种本质不同的解

在八皇后的92种解中有大量的解是本质重复的 可以通过左右对称,上下对称,对角线对称,旋转来互相转化 只有十二种解是本质不同的。 #include<stdio.h> int w=1; int check(int m); void put(void); int check3(void); int check2(void); void firstdiagonal(); void seconddiagonal(); void updown(); void leftright(); void Queen(

qq_51741975的博客 2430

NVIDIA 2025 Board Design Engineer 校招笔试

电路分析,矩形波阶跃反馈驱动​,误差信号。非常简单,数电or​离散基础。第一题是考试规矩知情确认。大二暑假做的,纯体验​。五六题太长,下篇分享。

m0_74253823的博客 1129

本地化搭建DeepSeek+RAGFlow,构建个人知识库

本地化搭建DeepSeek+RAGFlow,构建个人知识库。至少32G以上内存、500G以上空余磁盘空间。

gogospecter的专栏 7427

python八皇后游戏

【代码】python八皇后游戏。

qq_40753021的博客 567

单细胞转录组数据分析全流程:从原始数据到细胞注释

本文详细介绍了单细胞转录组数据分析的全流程,从原始数据读取、环境搭建、数据质控与标准化,到降维聚类、细胞类型注释,以及高级质控与多样本整合。重点阐述了如何利用Seurat等工具进行数据处理,并通过标志基因比对与自动注释方法完成细胞身份鉴定,为研究者提供了一套清晰、可操作的分析指南。

coffee的博客 553

JAVA八皇后与黑白皇后

因为一行只能放一个皇后 所以dfs传入的x(正在放第几个就可以作为传入的当前行)任意的两个黑皇后都不在同一行、同一列或同一条对角线上,任意的两个白皇。给定一个n×n的棋盘,现在要向棋盘中放入n个黑皇后和n个白皇后,使。一次dfs在一行同时放黑皇后和白皇后会比较复杂。我们先放完黑皇后再去放白皇后。可以记一下对角线的判定。问总共有多少种放法?

weixin_74234462的博客 263

I-Cache 和 D-Cache

I-Cache 和 D-Cache

liuyuanbin9001 7022

BIM模型导入SuperMap

目录 一、超图 BIM插件安装 1.1 插件下载 1.2 安装 二、BIM模型导出 2.1 Revit插件导出 2.2 SuperMap导入工具 三、SuperMap BIM数据处理与服务发布 四、SuperMap三维数据处理中关于模型高程修改方法 一、超图 BIM插件安装 1.1 插件下载 下载链接:http://support.supermap.com.cn/DownloadCenter/DownloadPage.aspx?tt=ProductAAS&id=134 1..

爱晒太阳的风 3597

八皇后及N皇后的回溯与递归算法

八皇后及N皇后的回溯与递归算法 // 8 queens #include int position[9]; // 第i个皇后的列号是position[i] (i:1-8) int check(int step){ int i; if(position[step]>8) return 0; for(i=1; i<step; i++){ if (

奋起的Coder。。。 1971

在 SAP BTP ABAP 环境中测试多租户 SaaS 解决方案的完整实践指南

ABAP SaaS测试阶段关键实践 在SAP BTP ABAP环境中开发多租户SaaS解决方案时,测试阶段(TST)对确保产品质量尤为关键。测试阶段应包含两个主要维度: 业务功能验证: 通过软件组件管理确保测试环境与代码仓库同步 创建并验证业务角色分配,确保权限配置正确 测试Fiori Launchpad导航流程和跨应用跳转 验证inbound/outbound通信配置 自动化质量管控: 在开发环境(DEV)执行本地ATC检查和单元测试 通过ABAP Test Cockpit(ATC)进行代码质量检查 集成

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 297

八皇后算法

//八皇后代码include

u012821276的专栏 236

【中科院一区Top-源码复现】Day-ahead photovoltaic power forecastingwith multi-source temporal-featureconvoluti

【中科院一区Top-源码复现】Day-ahead photovoltaic power forecastingwith multi-source temporal-featureconvoluti

739

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

N皇后 八皇后 位运算解法

位运算 八皇后 N皇后 问题描述 什么是八皇后? 题目链接 N皇后 解法 ​ 直接在N*N的棋盘上进行深搜,试探着下棋,也就是回溯法。 ​ 对于一个皇后来说,我们需要判断她的 八个方向 ,即 主对角线,副对角线,行,列 ​ 1. 确定状态 ​ 第一眼的感觉是要用 四个数组来储存情况,但实际上只需要三个 ,把 行 排除在外 ​ 因为每次搜索的时候,都自动按行搜索,也就是变量 row ,每改变一次,代...

weixin_34356555的博客 278

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

2024.12.07 n皇后 & 八皇后本质解

后续数字序列表示八皇后所在位置,数值本身表示某个皇后在棋盘上的行坐标,该数值所在位置表示该皇后的列坐标(>0),例如,数字5位于序列的第2位,表示棋盘上第5行第2列有一个皇后;数字4位于序列的第8位,表示棋盘上第4行第8列有一个皇后,由此,这8个数字描述了一种棋局。如果去除其中上下对称、左右对称棋局、主副对角线对称棋局和旋转后重复棋局,则有12种完全不同的棋局。例如,第一行输出 No1:1 5 8 6 3 7 2 4(冒号为西文冒号且前后无多余字符,冒号后的每个数字后均有一个西文空格),

2401_85766506的博客 492

深度学习工具包 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")

八皇后进阶之2n皇后

题目 1460: 蓝桥杯基础练习VIP-2n皇后问题 时间限制: 2s内存限制: 192MB提交: 3598 解决: 1781 题目描述 给定一个n*n的棋盘,棋盘中有一些位置不能放皇后。现在要向棋盘中放入n个黑皇后和n个白皇后,使任意的两个黑皇后都不在同一行、同一列或同一条对角线上,任意的两个白皇后都不在同一行、同一列或同一条对角线上。问总共有多少种放法?n小于等于8。 输入格式 输入的第一行为一个整数n,表示棋盘的大小。 n小于等于8 接下来n行,每行n个0或1的整数,如果一个整数为

2301_80221401的博客 465

蓝桥杯Day9学习——八皇后我终于是懂了

二分一道、八皇后+同DFS基础题、BFS基础。

2303_79931170的博客 841

C#写八皇后

C#写八皇后 引言 刚开始接触到C#是因为想要用Unity自己做游戏 ,把脑海里的创意落到屏幕前。 而所有的Unity教程里都是从C#起步,所以就想好好学门C# 任务 这是老师布置的作业: 2.3 在8X8格的国际象棋棋盘上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上。请输出尽可能多的摆法。 环境 Visual stdio 2019 思路 为了对棋盘的布局有个清晰地了解,我们可以这样想:任意两个皇后不能在同一行,那么就说明一行放一个皇后,那么只要找到每行的皇后分别放在

hanhandeguajian的博客 526

八皇后本质不同的解

8皇后本质不同的解 代码是自己写的,思路写在代码下方,希望可以和大家讨论~ 题目名称:八皇后本质不同的解 题目描述: 如上题所述,当N=8时,一共有92种可能。如果去除其中上下对称、左右对称棋局、主副对角线对称棋局和旋转后重复棋局,则有12种完全不同的棋局。编写程序,输出这12种棋局。 输入: 无 输出: 共12行,每行输出1种棋局, 例如,第一行输出 No1:1 5 8 6 3 7 2 4(冒号为西文冒号且前后无多余字符,冒号后的每个数字后均有一个西文空格), 其中No1 表示这是第1种棋局;后续数字序列

u010656213的博客 2291

蓝桥杯 八皇后

题目描述: 规则同 8 皇后问题,但是棋盘上每格都有一个数字,要求八皇后所在格子数字之和最大。 输入格式 一个8*8的棋盘。 输出格式 所能得到的最大数字和 样例输入 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42...

answer 404

皇后问题最快的解法(C语言)八皇后、十六皇后时间在毫秒级

//皇后问题最快的解法(C语言)八皇后、十六皇后时间在毫秒级 #include # include # include # include #define O 134775813 // TODO (xubo18056052430#1#): PB10210016 徐波 LARGE_INTEGER lv,lv1,lv2,lv3,lv4; double totaltime,secondsPer

Keep Learning 4024

Java学习之八皇后

八皇后,递归,回溯

wjkqq0921的博客 1204

P1219 [USACO1.5] 八皇后 Checker Challenge

本文介绍了P1219 [USACO1.5] 八皇后 Checker Challenge的解题思路和代码实现。题目要求在n×n的棋盘上放置n个皇后,使得每行、每列和每条对角线上至多有一个皇后。文章详细描述了输入输出格式,并提供了一个C++代码示例,使用深度优先搜索(DFS)算法来寻找所有可能的解。代码通过递归和回溯的方式,确保每行、每列和每条对角线上只有一个皇后,并输出前三个解及解的总数。最后,作者呼吁读者点赞并养成先赞后看的习惯。

zty20120913的博客 901
上一篇: nylgACM_105_九的余数
下一篇: java源码生成jar可执行文件
君只见独不见
博客等级 码龄12年 99粉丝 162原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值