1. 程式人生 > 實用技巧 >Acwing 1107. 魔板 BFS

Acwing 1107. 魔板 BFS

地址https://www.acwing.com/problem/content/description/1109/

Rubik 先生在發明了風靡全球的魔方之後,又發明了它的二維版本——魔板。

這是一張有 8 個大小相同的格子的魔板:

1 2 3 4
8 7 6 5
我們知道魔板的每一個方格都有一種顏色。

這 8 種顏色用前 8 個正整數來表示。

可以用顏色的序列來表示一種魔板狀態,規定從魔板的左上角開始,沿順時針方向依次取出整數,構成一個顏色序列。

對於上圖的魔板狀態,我們用序列 (1,2,3,4,5,6,7,8) 來表示,這是基本狀態。

這裡提供三種基本操作,分別用大寫字母 A,B,C 來表示(可以通過這些操作改變魔板的狀態):

A:交換上下兩行;
B:將最右邊的一列插入到最左邊;
C:魔板中央對的4個數作順時針旋轉。

下面是對基本狀態進行操作的示範:

A:

8 7 6 5 1 2 3 4 B: 4 1 2 3 5 8 7 6 C: 1 7 2 4 8 6 3 5 對於每種可能的狀態,這三種基本操作都可以使用。 你要程式設計計算用最少的基本操作完成基本狀態到特殊狀態的轉換,輸出基本操作序列。 注意:資料保證一定有解。 輸入格式 輸入僅一行,包括 8 個整數,用空格分開,表示目標狀態。 輸出格式 輸出檔案的第一行包括一個整數,表示最短操作序列的長度。 如果操作序列的長度大於0,則在第二行輸出字典序最小的操作序列。 資料範圍 輸入資料中的所有數字均為 18 之間的整數。 輸入樣例: 2 6 8 4 5 7 3 1 輸出樣例: 7 BCABCCB

解答

演算法1
嘗試用BFS解決 獲取最短路徑
變換的次序也是優先嚐試A 其次為B 最後為C。這樣就保證了最後的答案的字母序.
同時BFS保證了最短路徑。
比較坑的有兩點
1 雙層字串直接轉換成一維的字串的話 不是12345678 對映 1234 5678 ,
而是12345678 對映 1234 8765
2 三個變換的程式碼實現 要注意。

程式碼

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <queue>
#include 
<algorithm> using namespace std; vector<string> input(2); vector<string> start(2); map<vector<string>, string> mp; void init() { for (int i = 0; i < 4; i++) { char c; cin >> c; input[0] += c; } for (int i = 0; i < 4; i++) { char c; cin >> c; input[1] += c; } reverse(input[1].begin(), input[1].end()); start[0]=("1234"); start[1]=("8765"); } vector<string> ChangA(const vector<string>& vs) { vector<string> ret = vs; swap(ret[0], ret[1]); return ret; } vector<string> ChangB(const vector<string>& vs) { vector<string> ret = vs; for (int x = 0; x < 2; x++) { char tmp = ret[x][3]; for (int i = 3; i > 0; i--) { ret[x][i] = ret[x][i - 1]; } ret[x][0] = tmp; } return ret; } vector<string> ChangC(const vector<string>& vs) { vector<string> ret = vs; char tmp = ret[0][1]; ret[0][1] = ret[1][1]; ret[1][1] = ret[1][2]; ret[1][2] = ret[0][2]; ret[0][2] = tmp; return ret; } int main() { init(); queue<vector<string>> q; q.push(start); mp[start] = ""; while (q.size()) { vector<string> curr = q.front(); q.pop(); string path = mp[curr]; if (curr == input) { cout << path.size()<<endl; if(path.size()>0) cout << path << endl; return 0; } vector<string> nextA = ChangA(curr); string pathA = path + 'A'; vector<string> nextB = ChangB(curr); string pathB = path + 'B'; vector<string> nextC = ChangC(curr); string pathC = path + 'C'; if (mp.count(nextA) == 0) { q.push(nextA); mp[nextA] = pathA; } if (mp.count(nextB) == 0) { q.push(nextB); mp[nextB] = pathB; } if (mp.count(nextC) == 0) { q.push(nextC); mp[nextC] = pathC; } } return 0; }