算法实现流程:
步骤1:初始化马的位置(结构体horse {x, y})
步骤2:确定马从当前点出发,可跳跃的附近8个点,以结构体Jump数组给出,但需判断当前给出的附近8个点是否曾经访问过,或者是否这8个点超出棋盘尺寸。
步骤3:跟据步骤2确定跳跃的点,分别计算可跳跃点的下下一步,可跳跃点的个数。并选出下下步可跳跃点数最少的点作为马下一步跳跃的点。(举例说明:马当前所在点坐标(4,4),下一步可跳跃点有(5,2),(6,3),且(5,2)下一步可跳跃点有3个,(6,3)下一步可跳跃点2个;3 > 2这个时候,选择下下一跳小的点进行跳跃,则马下一跳为(6,3))
流程图:
#pragma once #include#include using namespace std; #define SAFE_DELETE(x) if (x != NULL) {delete(x); x = NULL;} #define SAFE_DELETE_ARR(x) if (x != NULL) {delete[](x); x = NULL;} #define PRING_ARR(title, arr, n) {cout << title << " "; for (int i=0; i 0) { min_cnt = INF; //棋子可跳八个方位 for (int i = 0; i < 8; i++) { forward_x = horse.x + jump[i].delx; forward_y = horse.y + jump[i].dely; //判断这两个坐标是否有效 if (forward_x < 0 || forward_x >= N || forward_y < 0 || forward_y >= N || altas[forward_x][forward_y] == 1) continue; w_cnt = 0; for (int j = 0; j < 8; j++) { forward_xx = forward_x + jump[j].delx; forward_yy = forward_y + jump[j].dely; if (forward_xx < 0 || forward_xx >= N || forward_yy < 0 || forward_yy >= N || altas[forward_xx][forward_yy] == 1) continue; w_cnt++; } if (min_cnt > w_cnt) { min_cnt = w_cnt; tmp_run_x = forward_x; tmp_run_y = forward_y; } } //棋子移动判断 if (min_cnt == INF) { cout << "没有找到可以移动的地方" << endl; break; } else { horse.x = tmp_run_x; horse.y = tmp_run_y; altas[tmp_run_x][tmp_run_y] = 1; cout <<"第"<< 63 - max_visit << "步," << "棋子当前移动到:" << "(" << tmp_run_x << ", " << tmp_run_y << ")" << endl; } } } }; #define _CRT_SECURE_NO_WARNINGS true #include "HorseRun.h" int main() { HorseRun app; return 0; }
运行结果输出1-63步马行驶的具体路径信息:
中间还有很多输出省略。。。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)