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

时间: 2024-04-28 08:20:23 浏览: 7
好的,我可以为您提供一个基于C++的A*算法实现八数码难题的搜索,以下是代码: ```cpp #include <iostream> #include <cstdio> #include <cstring> #include <queue> #include <algorithm> using namespace std; const int MAXN = 1e5 + 5; const int INF = 0x3f3f3f3f; int dx[4] = {0, 1, 0, -1}; int dy[4] = {1, 0, -1, 0}; int tar_pos[10][2] = {{0, 0}, {0, 1}, {0, 2}, {1, 0}, {1, 1}, {1, 2}, {2, 0}, {2, 1}, {2, 2}}; struct node { int x, y; int step; int f; char p[3][3]; bool operator < (const node& a) const { return f > a.f; } }; char tar[3][3] = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '0'}}; bool vis[MAXN]; int dis[MAXN], pos[MAXN]; priority_queue<node> q; inline int h(node& a) { int cnt = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (a.p[i][j] != '0') cnt += abs(i - tar_pos[a.p[i][j] - '0'][0]) + abs(j - tar_pos[a.p[i][j] - '0'][1]); return cnt; } inline int get_id(node& a) { int id = 0, base = 1; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) { pos[a.p[i][j] - '0'] = id++; id %= 9; } for (int i = 0; i < 9; i++) { int cnt = 0; for (int j = i + 1; j < 9; j++) if (pos[j] < pos[i]) cnt++; id += cnt * base; base *= (9 - i); } return id; } int main() { node st; memset(vis, false, sizeof(vis)); memset(dis, INF, sizeof(dis)); st.step = 0; st.f = h(st); for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) { cin >> st.p[i][j]; if (st.p[i][j] == '0') { st.x = i; st.y = j; } } q.push(st); vis[get_id(st)] = true; dis[get_id(st)] = 0; while (!q.empty()) { node t = q.top(); q.pop(); vis[get_id(t)] = false; if (t.f == t.step) { cout << t.step << endl; return 0; } for (int i = 0; i < 4; i++) { int nx = t.x + dx[i]; int ny = t.y + dy[i]; if (nx >= 0 && nx < 3 && ny >= 0 && ny < 3) { node s = t; swap(s.p[t.x][t.y], s.p[nx][ny]); s.x = nx; s.y = ny; s.step = t.step + 1; s.f = s.step + h(s); int id = get_id(s); if (s.step < dis[id]) { dis[id] = s.step; if (!vis[id]) { vis[id] = true; q.push(s); } } } } } return 0; } ``` 该代码中,我们使用了优先队列来实现A*算法的搜索过程,通过`h()`函数来计算当前状态与目标状态之间的估价函数值,再通过优先队列来计算最优解。其中,get_id()函数用于计算当前状态的哈希值,防止重复搜索。 该代码通过输入一个初始状态,计算出最小步数,使得该状态可以通过移动1~8数字到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的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。