国际马的跳法
2016-04-20 06:37
393 查看
问题:国际象棋的棋盘上,马从左上角跳到跳到右下角,总共有几种跳法。
这个问题与中国象棋的棋盘上的跳马问题完全相同,只是起始和终止坐标的不同。但是,可以比较一下所有跳法的数量,了解问题复杂度的差异。
求所有跳法,需要用穷尽搜索,试探法即回溯法是首选。
程序中,以左上角坐标为(0,0),马从左上角(0,0)跳到右下角(7,7)。
马在某个位置,一般而言有8种跳法,但是由于规定只能往右跳,所以只有4种跳法。同时如果跳出棋盘外则回溯。
为了在马跳到目的地后输出结果,使用堆栈存储马跳的轨迹。
总共有18种跳法。与中国象棋半张棋盘上37种跳法相比,可以说中国象棋问题的复杂度更高。
这个问题与中国象棋的棋盘上的跳马问题完全相同,只是起始和终止坐标的不同。但是,可以比较一下所有跳法的数量,了解问题复杂度的差异。
求所有跳法,需要用穷尽搜索,试探法即回溯法是首选。
程序中,以左上角坐标为(0,0),马从左上角(0,0)跳到右下角(7,7)。
马在某个位置,一般而言有8种跳法,但是由于规定只能往右跳,所以只有4种跳法。同时如果跳出棋盘外则回溯。
为了在马跳到目的地后输出结果,使用堆栈存储马跳的轨迹。
总共有18种跳法。与中国象棋半张棋盘上37种跳法相比,可以说中国象棋问题的复杂度更高。
/* * * 问题描述:国际象棋的棋盘上,一匹马从左上角跳到右下角,只允许往右跳, * 给出各种跳法。 * * 国际象棋跳马问题算法程序 * */ #include <stdio.h> #define STACK_SIZE 100 struct stack { int row; int col; } stack[STACK_SIZE]; int ps = 0; int count = 0; void horse(int row, int col); void push(int row, int col); void pop(); void output_result(); int main(void) { horse(0, 0); return 0; } void horse(int row, int col) { push(row, col); if(row == 7 && col == 7) output_result(); if(row < 0 || row > 7 || col > 7) { ; } else { horse(row - 2, col + 1); horse(row - 1, col + 2); horse(row + 1, col + 2); horse(row + 2, col + 1); } pop(); } void push(int row, int col) { stack[ps].row = row; stack[ps].col = col; ps++; } void pop() { ps--; } void output_result() { count++; int i; printf("result %d\n", count); for(i=0; i<ps; i++) { printf("%2d: %d %d\n", i+1, stack[i].row, stack[i].col); } printf("\n"); getchar(); }
相关文章推荐
- LeetCode 131. Palindrome Partitioning
- 中国马的跳法
- Jinja2
- android 通用圆角控件
- 第一冲刺阶段——站立会议第三天4月20日
- Android学习(29) --ListView
- mina客户端架构
- Android学习(28) -- 动态创建TextView并展示数据
- LeetCode 200. Number of Islands
- maven
- 摘抄:顶级高频交易团队
- 数据类型总结(C++,C#)
- mina服务器端架构
- 安装Office2016,桌面没有PPT图标,右键新建没有图标
- strtok函数()
- LeetCode 90. Subsets II
- leetcode 237. Delete Node in a Linked List
- leetcode 283. Move Zeroes
- android二维码生成器 艺术二维码
- 开通自己的技术博客了,欢迎大家前来指正