《挑战程序设计竞赛(疑惑)》19.2九宫格拼图
生活随笔
收集整理的這篇文章主要介紹了
《挑战程序设计竞赛(疑惑)》19.2九宫格拼图
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
不知道為什么用二維數組來實現不能,留給未來的我來解決吧。
#define N 3 #define M 4#include <iostream> #include<string> #include<queue> #include<map> using namespace std; struct Puzzle {int grids[N][N];//拼圖坐標的二維數組描述string path = "";//路徑int space_x;int space_y;//目標點的坐標bool operator < (const Puzzle &p) const{for (int i = 0; i < N; i++){for (int j = 0; j < N; j++){if (grids[i][j] == p.grids[i][j]) continue;return grids[i][j]< p.grids[i][j];}}return false;} }; //確立方向的變化 static const char dir[M] = {'L','R','U','D'}; static const int dx[M] = {0, 0, -1, 1}; static const int dy[M] = {-1, 1, 0, 0}; bool is_target(Puzzle tp)//判斷是否到達目標狀態 {for (int i = 0; i < N; i++){for (int j = 0; j < N; j++){if (tp.grids[i][j] != (3 * i + j + 1)){return false;}}}return true; }string bfs(Puzzle tp)//用寬度搜索進行狀態轉移 {Puzzle tp2;queue<Puzzle> qu;map<Puzzle, bool>Cut;tp.path = "";qu.push(tp);Cut[tp] = true;while(!qu.empty()){printf("1\n");tp2 = qu.front(); qu.pop();if (is_target(tp2)) {return tp2.path;}for (int i = 0; i < M; i++){int space_x = tp2.space_x+dx[i];int space_y = tp2.space_y+dy[i];if (space_x < 0 || space_y < 0 || space_x >= N || space_y >= N){continue;}swap(tp2.grids[tp2.space_x][tp2.space_y], tp2.grids[space_x][space_y]);tp2.space_x = space_x;tp2.space_y = space_y;if (!Cut[tp2]){Cut[tp2] = true;tp2.path += dir[i];qu.push(tp2);}}}return "unsolvable"; }int main() {Puzzle sp;//初始化拼圖坐標for (int i = 0; i < N; i++){for (int j = 0; j < N; j++){cin>>sp.grids[i][j];if (sp.grids[i][j] == 0){sp.grids[i][j] = N*3;sp.space_x = i;sp.space_y = j;}}}for (int i = 0; i < N; i++){for (int j = 0; j < N; j++){cout << sp.grids[i][j]<<" ";}cout<<"\n";}cout << is_target(sp)<<"\n";string ans = bfs(sp);cout << ans;system("pause");return 0; }總結
以上是生活随笔為你收集整理的《挑战程序设计竞赛(疑惑)》19.2九宫格拼图的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: uap 自动生成场景代码
- 下一篇: 匈牙利算法的Java语言实现