趣味算法-马踏棋盘
2012-02-14 22:36
281 查看
趣味算法-马踏棋盘
国际象棋64个格,按照马的走法,踏遍棋盘的每个格。
1) 使用递归算法尝试下一步是否满足条件,不满足条件则回退。
2) 若所有的格都被尝试一次则成功。
国际象棋64个格,按照马的走法,踏遍棋盘的每个格。
1) 使用递归算法尝试下一步是否满足条件,不满足条件则回退。
2) 若所有的格都被尝试一次则成功。
#include <stdio.h> typedef struct _next_pos { int m_x; int m_y; } next_pos_t; next_pos_t next_pos[8]={{-1,2},{-2,1},{-2,-1},{-1,-2}, {1,-2},{2,-1},{2, 1},{ 1, 2}}; int chess[8][8]; int nResult = 0; next_pos_t arrRes[64]; int move(int nPosX, int nPosY) { int i = 0; int nRet = 0; for (i=0; i<8; i++) { if ((nPosX+next_pos[i].m_x < 0) || (nPosX+next_pos[i].m_x > 7) || (nPosY+next_pos[i].m_y < 0) || (nPosY+next_pos[i].m_y > 7)) { continue; } if (chess[nPosX+next_pos[i].m_x][nPosY+next_pos[i].m_y] == 0) { chess[nPosX+next_pos[i].m_x][nPosY+next_pos[i].m_y] = 1; nResult++; arrRes[nResult].m_x = nPosX+next_pos[i].m_x; arrRes[nResult].m_y = nPosY+next_pos[i].m_y; nRet = move(nPosX+next_pos[i].m_x, nPosY+next_pos[i].m_y); if (nRet == -1) { chess[nPosX+next_pos[i].m_x][nPosY+next_pos[i].m_y] = 0; nResult--; } } } if (nResult == 63) nRet = 0; else nRet = -1; return nRet; } int main() { int i = 0; memset(chess, 0, sizeof(chess)); memset(arrRes,0, sizeof(arrRes)); arrRes[0].m_x=0; arrRes[0].m_y=0; i = move(0, 0); if (i == 0) { printf("find the solution\n"); for (i=0;i<64;i++) { if (i%8 == 0) { printf("\n"); } printf("X=%d Y=%d; ", arrRes[i].m_x, arrRes[i].m_y); } } scanf("%d", &i); return 0; }
相关文章推荐
- 【趣味算法设计】众数问题&社会名流问题
- 趣味理解匈牙利算法(转载)
- 趣味数学-鸡兔同笼算法
- 趣味算法:字符串反转的N种方法
- 2015 年 JXNU_ACS 算法组寒假第一次周赛 1008 趣味数学题
- 趣味算法:老鼠试毒瓶问题
- 趣味算法:国王和100个囚犯(据说是腾讯的面试题)
- 趣味算法:老鼠试毒瓶问题
- 趣味算法:猴子搬香蕉问题
- 算法—趣味理解分治算法
- 蓝桥杯 算法训练 Hankson的趣味题(数论)
- 趣味算法-Hanoi
- (转)趣味算法:字符串反转的N种方法
- 大数据早报:时装设计也用上了人工智能,亚马逊研究出新算法;上海地铁趣味消费数据发布(9.12)
- 趣味算法-城市之间最短总距离
- 趣味算法-青蛙过河
- 趣味算法-巧填运算符
- 二分图的最大匹配 ————匈牙利算法 (转载了一个大神的趣味算法) poj3041(Asteroids)
- 趣味算法-0的迷宫
- C# 趣味小程序算法(1)—— 旋转阵