uva10085
来源:互联网 发布:深圳网络诈骗举报 编辑:程序博客网 时间:2024/06/10 11:52
题目大意:
这一题跟八编码的题目有些类似,但是它并不是求目标状态,它所求的是可以达到的最远的那个图。
思路:
第一次接触这样的题目,看了题解才过的。
使用到了哈希判重和bfs,还需要递归的打印路径。
#include <iostream>using namespace std;#include <cstring>#include <stdio.h>typedef int State[9];const int MAXSTATE = 1000000;int state[9];State st[MAXSTATE],goal;int father[MAXSTATE],path[MAXSTATE],ans;char path_dir[5] ="UDLR";int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};const int MAXHASHSIZE = 1000003;int head[MAXHASHSIZE],next1[MAXSTATE];void init_lookup_table () { memset(head,0,sizeof(head));}int hash1(State &s );int try_to_insert(int s) { int h = hash1(st[s]); int u = head[h]; while(u) { if(memcmp(st[u],st[s],sizeof(st[s])) == 0) return 0; u = next1[u]; } next1[s] = head[h]; head[h] = s; return 1;}void bfs() { init_lookup_table(); father[0] = path[0] =-1; int front = 0 ,rear =1; memcpy(st[0],state,sizeof(state)); try_to_insert(0); while(front < rear) { int *s =st[front]; int j; for(j = 0; j <9; j++) if(!s[j]) break; int x = j/3,y = j%3; for(int i = 0 ; i <4; i++) { int dx = x+ dir[i][0]; int dy = y + dir[i][1]; int pos = dx * 3 + dy; if(dx >= 0 && dx <3 && dy >=0 && dy <3) { int *newState = st[rear]; memcpy(newState,s,sizeof(int)*9); newState[j] = s[pos]; newState[pos] = 0; if(try_to_insert(rear)) { father[rear] = front; path[rear] = i; rear++; } } } front ++; } ans = rear -1;}int hash1(State &s) { int v = 0; for(int i = 0; i <9 ;i++) v = v * 10 + s[i]; return v% MAXHASHSIZE;}void print_path(int cur) { if(cur!= 0) { print_path(father[cur]); printf("%c",path_dir[path[cur]]); }}int main() { int T,cas = 1; scanf("%d",&T); while(T--) { for(int i = 0; i < 9; i++) scanf("%d",&state[i]); bfs(); printf("Puzzle #%d\n",cas++); for(int i = 0; i <3; i++) printf("%d %d %d\n",st[ans][i*3],st[ans][i*3+1],st[ans][i*3+2]); print_path(ans); printf("\n\n"); } return 0;}
0 0
- UVA10085
- uva10085
- uva10085
- UVa10422和UVa10085
- UVa10085 - The most distant state
- uva10085 - The most distant state
- UVa10085 - The most distant state
- [隐式图搜索]The most distant state UVA10085
- uva10085(The Most Distant State)-隐式图搜索
- uva10085 The most distant state(BFS)
- UVA10085宽搜之八宫格走最远
- 4-12 判断奇偶性
- Riemann积分和Lebesgue积分角度下一积分不等式的等号成立充要条件的研究
- Chapter 2 部分手记
- android设计模式之mvp详解
- 初探 iOS8 中的 Size Class
- uva10085
- 响应式布局
- Android Studio——用Android访问本地站点---(localhost,10.0.2.2)要区别
- leetcode 319 Bulb Switcher
- springMVC入门
- Android读取SQLite数据库中的中文
- 对于 gevent 的总结
- C语言:快速排序
- Eclipse集成Tomcat(web容器)