马踏棋盘算法
2021/11/18 22:13:15
本文主要是介绍马踏棋盘算法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
问题:在N行N列的棋盘上,一位骑士按象棋中“马走日”的走法从初始坐标位置(SX, SY)出发,
要求遍历(巡游)棋盘中每一个位置一次。请输出其实巡游的位置顺序,或输出无解。
#include <iostream> using namespace std; // 棋盘边长、起始位置、总步数 const int N = 5, SI = 0, SJ = 0, STEPS = N*N - 1; int map[N][N];// 棋盘数组,存储遍历序号 static int ways;// 遍历的方法数 bool move(int si, int sj, int steps){ if (si < 0 || si > N - 1 || sj<0 || sj>N - 1){ return false;// 越界 } if (map[si][sj] != 0){ return false;// 已被访问过 } if (steps == 0){ ways++; return true;// 成功遍历一次 } steps--;// 剩余步数-1 map[si][sj] = STEPS - steps;// 存储遍历序号 // 八个位置逐一尝试是否可行,直至全部不可行 if (move(si + 1, sj + 2, steps) == true)return true; if (move(si + 1, sj - 2, steps) == true)return true; if (move(si - 1, sj + 2, steps) == true)return true; if (move(si - 1, sj - 2, steps) == true)return true; if (move(si + 2, sj + 1, steps) == true)return true; if (move(si + 2, sj - 1, steps) == true)return true; if (move(si - 2, sj + 1, steps) == true)return true; if (move(si - 2, sj - 1, steps) == true)return true; map[si][sj] = 0;// 全部不可行,往后退一步,这一步不能存下来 return false;// 表明此路不通 } void main(){ if (move(SI, SJ, STEPS) == true){ for (int i = 0; i < N; i++){ for (int j = 0; j < N; j++){ cout.fill('0');// 设置填充字符 cout.width(2);// 设置域宽 cout << map[i][j] << " ";// 输出遍历序号 } cout << endl; } } else{ cout << "No path found!" << endl;// 没有可遍历的路线 } }
这篇关于马踏棋盘算法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)