八数码之A*解决方法
来源:互联网 发布:就业前景好的专业知乎 编辑:程序博客网 时间:2024/05/28 16:06
学习过A*算法后,通过计算出每个节点的f值,在把队列里的节点通过对f的大小进行排列。
f=h+g
g是已经走过的步数,h为还需要最少的步数。
#include<iostream>using namespace std;const int MAXX = 1000000;struct Node{ char tile[10]; int pos; int parents; int g,f; int pre;};int cmp(const void*a, const void *b){ if ((*(Node*)a).f == (*(Node*)b).f) return ((*(Node*)a).g == (*(Node*)b).g); return ((*(Node*)a).f - (*(Node*)b).f);}int _move[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };char pre[4] = { 'r', 'l', 'd', 'u' };Node qu[MAXX];int front, tail,b;char _start[10],_end[10]="12345678x";void init(){ front = tail = 0; qu[tail++].parents = -1; strcpy(qu[0].tile, _start); qu[0].pos = strchr(_start, 'x') - _start; qu[0].g = 0; b = 0;}int isexit(Node node){ for (int i = 0; i<tail; i++){ if (strcmp(qu[i].tile, node.tile) == 0) return 1; } return 0;}int getF(Node node){ int temp = 0; for (int i = 0; i < 9; i++){ if (node.tile[i] != _end[i]) temp++; } return temp;}void show(Node temp){ if (temp.parents != 0){ show(qu[temp.parents]); } cout << pre[temp.pre];}void dfs(){ Node temp,now; int x, y; while (tail-front>0) { qsort(qu + front, tail - front, sizeof(Node), cmp); now = qu[front++]; //找到答案 if (strcmp(now.tile, _end) == 0){ b = 1; show(now); cout << endl; return; } temp.g = now.g + 1; for (int i = 0; i < 4; i++){ strcpy(temp.tile, now.tile); x = now.pos / 3 + _move[i][0]; y = now.pos % 3 + _move[i][1]; if (x < 0 || x >= 3 || y < 0 || y >= 3) continue; temp.pos = x * 3 + y; temp.tile[now.pos] = now.tile[temp.pos]; temp.tile[temp.pos] = 'x'; if (isexit(temp)){ continue; } temp.parents = front - 1; temp.pre = i; temp.f = temp.g+getF(temp); qu[tail++] = temp; } }}int main(){ char str[50]; while (gets(str)){ int ans= 0; for (int i = 0; str[i]; i++){ if (str[i] != ' ') _start[ans++] = str[i]; } if (strcmp(_start, _end) == 0) cout << "lr" << endl; else { init(); dfs(); if (!b) cout << "unsolvable" << endl; } } return 0;}
0 0
- 八数码之A*解决方法
- 八数码之双广解决方法
- 八数码A*搜索
- A*,八数码
- A星八数码
- hdu1043【八数码】【A*】
- 八数码 A*算法
- PKU-1077 Eight (八数码之A*算法)
- a*八数码(有问题)
- 八数码(A* 735ms)
- 八数码(A星)
- 八数码游戏 A*算法
- 八数码问题A*算法
- hdu 1043 八数码 A*
- 八数码问题-A*算法
- poj-1077 八数码 【a*】
- 八数码问题--A*算法
- A*搜索 - 八数码问题
- JAVA中的abstract理解
- git入门(4)-Git rebase
- 63.View the Exhibit and examine the structure of the PRODUCTS table.
- C/C++从文件开头按行读取内容==并无需新建文件,获取前部分内容
- 位操作
- 八数码之A*解决方法
- 网页端实用工具整理(纯个人向)
- Python爬虫入门一之综述
- Android Studio module里面放switch语句报错 R文件找不到
- 2016-03-03 名句诗
- 小范围排序
- [从头学数学] 第117节 相交线与平行线 小结与复习题
- 64.View the Exhibit and examine the data in the PROMO_CATEGORY and PROMO_COST columns of
- Profiler内存查看|Navmesh动态加载...