本文主要是介绍马踏棋盘问题(贪心算法实现C++),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
算法实现流程:
步骤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 <iostream>
#include <math.h>
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<n; i++) {cout << arr[i] << " ";} cout << endl;}#define INF 9999999typedef struct
{int x;int y;
}Location;typedef struct
{int delx;int dely;
}Jump;class HorseRun
{
private:int** altas;int N; //棋盘的宽Location horse; //马当前的位置
public:HorseRun(){N = 8;altas = new int* [N]();for (int j = 0; j < N; j++){altas[j] = new int[N]();memset(altas[j], 0, sizeof(int) * N);}//随机生成马的初始位置horse = { rand() % N, rand() % N };altas[horse.x][horse.y] = 1;cout << "马初始位置:" << "(" << horse.x << "," << horse.y << ")" << endl;Visit();}~HorseRun(){for (int i = 0; i < N; i++)SAFE_DELETE_ARR(altas[i]);SAFE_DELETE_ARR(altas);}inline void Visit(){Jump jump[8] = { {1,-2}, {2, -1}, {2, 1}, {1, 2}, {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2} };int max_visit = 63;int forward_x, forward_y, forward_xx, forward_yy, w_cnt, min_cnt, tmp_run_x, tmp_run_y;while (max_visit-- > 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步马行驶的具体路径信息:
中间还有很多输出省略。。。
这篇关于马踏棋盘问题(贪心算法实现C++)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!