用c++ 利用A*算法实现八数码难题(九宫重排)的搜索。

时间: 2023-07-20 13:26:05 浏览: 49
好的,下面是C++代码实现: ```cpp #include<iostream> #include<queue> #include<map> #include<vector> #include<algorithm> using namespace std; const int n = 3; // 九宫格大小 const int maxn = 9; // 九宫格中数字个数 // 状态节点类 class StateNode { public: int state[maxn]; // 当前状态 int empty_pos; // 空格位置 int g; // 到达当前状态的路径长度 int h; // 启发式函数估计的距离值 StateNode() {} StateNode(int* s, int e, int g, int h) : empty_pos(e), g(g), h(h) { for (int i = 0; i < maxn; i++) { state[i] = s[i]; } } // 获取空格上方状态 StateNode get_up_state() { int* new_state = new int[maxn]; for (int i = 0; i < maxn; i++) { new_state[i] = state[i]; } swap(new_state[empty_pos], new_state[empty_pos - n]); return StateNode(new_state, empty_pos - n, g + 1, manhattan(new_state)); } // 获取空格下方状态 StateNode get_down_state() { int* new_state = new int[maxn]; for (int i = 0; i < maxn; i++) { new_state[i] = state[i]; } swap(new_state[empty_pos], new_state[empty_pos + n]); return StateNode(new_state, empty_pos + n, g + 1, manhattan(new_state)); } // 获取空格左侧状态 StateNode get_left_state() { int* new_state = new int[maxn]; for (int i = 0; i < maxn; i++) { new_state[i] = state[i]; } swap(new_state[empty_pos], new_state[empty_pos - 1]); return StateNode(new_state, empty_pos - 1, g + 1, manhattan(new_state)); } // 获取空格右侧状态 StateNode get_right_state() { int* new_state = new int[maxn]; for (int i = 0; i < maxn; i++) { new_state[i] = state[i]; } swap(new_state[empty_pos], new_state[empty_pos + 1]); return StateNode(new_state, empty_pos + 1, g + 1, manhattan(new_state)); } // 获取所有可行的子状态 vector<StateNode> get_all_next_states() { vector<StateNode> next_states; if (empty_pos >= n) { next_states.push_back(get_up_state()); } if (empty_pos < maxn - n) { next_states.push_back(get_down_state()); } if (empty_pos % n != 0) { next_states.push_back(get_left_state()); } if (empty_pos % n != n - 1) { next_states.push_back(get_right_state()); } return next_states; } // 获取曼哈顿距离 int manhattan(int* s) { int distance = 0; for (int i = 0; i < maxn; i++) { if (s[i] == 0) { continue; } int row = s[i] / n; int col = s[i] % n; distance += abs(row - i / n) + abs(col - i % n); } return distance; } // 重载运算符<,用于优先队列排序 bool operator < (const StateNode& other) const { return g + h > other.g + other.h; } // 判断是否为目标状态 bool is_target() { for (int i = 0; i < maxn; i++) { if (state[i] != i) { return false; } } return true; } // 输出状态 void output_state() { for (int i = 0; i < maxn; i++) { cout << state[i] << " "; if ((i + 1) % n == 0) { cout << endl; } } cout << endl; } }; // A*算法搜索 bool a_star_search(StateNode& start_state) { priority_queue<StateNode> q; map<int, bool> visited; q.push(start_state); visited[*start_state.state] = true; while (!q.empty()) { StateNode node = q.top(); q.pop(); if (node.is_target()) { node.output_state(); return true; } vector<StateNode> next_states = node.get_all_next_states(); for (int i = 0; i < next_states.size(); i++) { int* s = next_states[i].state; if (!visited[*s]) { q.push(next_states[i]); visited[*s] = true; } } } return false; } int main() { int start[maxn] = { 2, 8, 3, 1, 6, 4, 7, 0, 5 }; // 初始状态 int empty_pos = 7; // 空格位置 StateNode start_state(start, empty_pos, 0, 0); if (!a_star_search(start_state)) { cout << "无解" << endl; } return 0; } ``` 希望我的代码能够帮到你,如果你有其他问题,可以继续问我哦。

相关推荐

最新推荐

recommend-type

人工智能 A*算法 八数码问题 C++ 报告+代码+详细注释

使用C++语言完整的实现了A星算法解决八数码问题 内容:完整代码和详细注释; 主要函数的功能说明; 评价函数的设计; 运行测试结果
recommend-type

A*算法解八数码问题(报告附录里有源代码),保准能运行

C++实现的A*算法解八数码问题,报告的附录里有源代码,在VC6.0的环境下开发运行的
recommend-type

用C++实现DBSCAN聚类算法

本篇文章是对使用C++实现DBSCAN聚类算法的方法进行了详细的分析介绍,需要的朋友参考下
recommend-type

C++实现分水岭算法(Watershed Algorithm)

主要为大家详细介绍了C++实现分水岭算法Watershed Algorithm,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
recommend-type

C++使用递归和非递归算法实现的二叉树叶子节点个数计算方法

主要介绍了C++使用递归和非递归算法实现的二叉树叶子节点个数计算方法,涉及C++二叉树的定义、遍历、统计相关操作技巧,需要的朋友可以参考下
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

2. 通过python绘制y=e-xsin(2πx)图像

可以使用matplotlib库来绘制这个函数的图像。以下是一段示例代码: ```python import numpy as np import matplotlib.pyplot as plt def func(x): return np.exp(-x) * np.sin(2 * np.pi * x) x = np.linspace(0, 5, 500) y = func(x) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.title('y = e^{-x} sin(2πx)') plt.show() ``` 运行这段
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。