题意:有8个立方体,按相同颜色着色,相对面是相同颜色,按同一方向摆成3*3的方阵。问从初始状态到目标状态最少移动步数。
分析:题目是最短路径题,可以bfs可以回溯,用回溯加剪枝。不能走的格子是上次走的空格。
# include # include # include # include # include # include #include # include using namespace std;struct node {int top, front; }; int goal[3][3]; node start[3][3]; int dx[] = { 1,-1,0,0 }; int dy[] = { 0,0,1,-1 }; int step = 31; int judge() {int t = 0;for (int i = 0; i < 3; i++) {for (int j = 0; j < 3; j++) {if (start[i][j].top != goal[i][j])t++;}}return t; } void move(int x,int y,int i) {int ddx = x + dx[i]; int ddy = y + dy[i];if (i == 0 || i == 1) {swap(start[x][y].front, start[x][y].top);}else {start[x][y].top = 1 ^ 2 ^ 3 ^ start[x][y].front^start[x][y].top;}swap(start[x][y], start[ddx][ddy]); } void dfs(int curx,int cury,int layer) {if (layer > 30)return;int jp = judge();if (jp==0) {step = min(step, layer);return;}if (jp + layer > step)return;//剪枝int tx, ty;for(int i=0;i<3;i++)for(int j=0;j<3;j++)if (!start[i][j].top) {tx = i; ty = j; break;}for (int i = 0; i < 4; i++) {int ddx = tx + dx[i];int ddy = ty + dy[i];if (ddx >= 0 && ddx < 3 && ddy>=0 && ddy < 3 && (ddx != curx || ddy != cury)) {move(ddx, ddy, i ^ 1);dfs(tx, ty, layer + 1);move(tx, ty, i);}} } int main() {int ex, ey;char k;//0-empty,1-red,2-blue,3-whitewhile (cin >> ey >> ex && ex&&ey) {ex--; ey--;step = 31;for (int i = 0; i < 3; i++)for (int j = 0; j < 3; j++) {cin >> k;if (k == 'E')goal[i][j] = 0;else if (k == 'W')goal[i][j] = 3;else if (k == 'R')goal[i][j] = 1;else if (k == 'B')goal[i][j] = 2;if (ex == i && ey == j) {start[i][j].front = 0; start[i][j].top = 0;}else {start[i][j].front = 1; start[i][j].top = 3;}}dfs(-1, -1, 0);step = step > 30 ? -1 : step;cout << step << endl;}return 0; }
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
Duilib中list控件支持ctrl和shif多行选中的实现
[ICML2015]Batch Normalization:Accelerating Deep Network Training by Reducing Internal Covariate Shif
win10系统 微软输入法 于eclipse ctrl+shif+f冲突间接处理办法
Codeforces Round #259 (Div. 2) B. Little Pony and Sort by Shif
读LDD3,内存映射与DMA--PAGE_SHIF…
VMware虚拟机安装XP【要先分区,再设置BOOT 启动CD,shif+上移】
更换iBus五笔的左与右Shif
sublime ctrl+shif+f 没用解决办法
idea 对 ctrl + z 的撤销 是 ctrl + shif + z
计算机最早的设计师应用于,计算机应用基础选择题doc.doc
win10自带截图神器:Win+Shift+S
Python基础之文件目录操作
python简述目录_Python基础之文件目录操作(示例代码)
tp5 如何做数据采集
任务2-7(服务器字体+阿里巴巴矢量库)
html标签(1):h1~h6,p,br,pre,hr
TI 电量计介绍与芯片选型指南
几款TI电源芯片简介
TI DSP芯片C2000系列读取FLASH数据
德州仪器(Ti)平台嵌入式开发基础
TI三相电机智能栅极驱动芯片特点分类
省选模拟(12.08) T3 圈圈圈圈圈圈圈圈
Hadoop生态圈技术栈(上)
大数据开发基础入门与项目实战(三)Hadoop核心及生态圈技术栈之6.Impala交互式查询
小猿圈之Linux下Mysql 操作命令
大数据Hadoop生态圈常用面试题
大数据开发基础入门与项目实战(三)Hadoop核心及生态圈技术栈之4.Hive DDL、DQL和数据操作
备战Noip2018模拟赛11(B组)T3 Monogatari 物语
【智能优化算法-圆圈搜索算法】基于圆圈搜索算法Circle Search Algorithm求解单目标优化问题附matlab代码
NYOJ 78 圈水池
递归问题 跑道 汽车 绕圈问题 Python实现
Hadoop生态圈(三):MapReduce
微信公众账号
微信扫一扫加关注