日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

九宫重排

發(fā)布時間:2025/3/20 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 九宫重排 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

描寫敘述

如以下第一個圖的九宮格中,放著 1~8 的數(shù)字卡片,另一個格子空著。與空格子相鄰的格子中的卡片能夠移動到空格中。經(jīng)過若干次移動。能夠形成第二個圖所看到的的局面。我們把第一個圖的局面記為:12345678.把第二個圖的局面記為:123.46758顯然是按從上到下。從左到右的順序記錄數(shù)字,空格記為句點。本題目的任務(wù)是已知九宮的初態(tài)和終態(tài),求最少經(jīng)過多少步的移動能夠到達。假設(shè)不管多少步都無法到達,則輸出-1。


?

輸入

 輸入第一行包括九宮的初態(tài),第二行包括九宮的終態(tài)。

輸出

 輸出最少的步數(shù),假設(shè)不存在方案,則輸出-1。

例子輸入

12345678.
123.46758

例子輸出

3

#include <iostream> #include <cstring> #include <cstdio> #include <queue> using namespace std; char str1[20];///終態(tài) int jc[10] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};///1到10的階乘 int dir[] = {0, 1, 0, -1, 0};///方向 bool f[1000000]; struct node {char str[10];//當然狀態(tài)int step;//步數(shù)int loc;//空格位置 }; int fun(char str[])//狀態(tài)匹配 {for (int i = 0; i < 9; i++) {if (str[i] != str1[i])return false;}return true; } int por(string a)//康托展開 {int size = 0;for (int i = 0; i < 9; i++) {int len = 0;for (int j = i + 1; j < 9; j++) {if (a[i] > a[j])len++;}size += len * jc[8 - i];}return size; } int bfs(node x) {queue<node>q;q.push(x);while (!q.empty()) {node a = q.front();q.pop();for (int i = 0; i < 4; i++) {//四個方向// cout<<a.str<<endl;node b = a;int ax = b.loc / 3 + dir[i];int ay = b.loc % 3 + dir[i + 1];if (ax < 0 || ax >= 3 || ay < 0 || ay >= 3)continue;b.str[b.loc] = b.str[ax * 3 + ay];//位置交換b.str[ax * 3 + ay] = '9';b.loc = ax * 3 + ay;b.step ++;int index = por(b.str);if (!f[index]) {if (fun(b.str)) {return b.step;}f[index] = true;q.push(b);}}}return -1; } int main() {node a;while (cin >> a.str >> str1) {memset(f, 0, sizeof(f));for (int i = 0; i < 9; i++){if (a.str[i] == '.') {a.str[i] = 9; a.loc = i; a.step = 0;}if(str1[i]=='.')str1[i]='9';}cout << bfs(a) << endl;}return 0; }

總結(jié)

以上是生活随笔為你收集整理的九宫重排的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。