1.題目
2.解決方法
本題仍然是運用a*演算法求解,將狀態中每個數距離自己合法位置的曼哈頓距離之和作為估價函式,將估價函式與距離起點狀態的實際距離作為估計值,搜尋中的每個狀態都有乙個這樣的估計值,用小根堆使每次搜尋擴充套件結點時保證是估計值最小的狀態(也就是最短路徑上的狀態)
3.**
#include
#include
#include
#include
#include
#include
#include
#define x first
#define y second
using
namespace std;
typedef pair<
int,string> pis;
int dx=
,dy=
;char op=
;unordered_mapchar
,string>
> pre;
unordered_mapint> dist;
//估價函式:狀態中每個元素到它合法位置的曼哈頓距離之和
intcalc_maha
(string state)
}return res;
}int
bfs(string start,string end));
dist[start]=0
;while
(!heap.
empty()
)
string source=state;
for(
int i=
0;i<
4;i++);
heap.
push()
;}swap
(state[a*
3+b]
,state[x*
3+y]);
}}}int
main
(void
)
end=
"12345678x"
;int cnt=0;
for(
int i=
0;i<
(int
)seq.
size()
;i++
)for
(int j=i+
1;j<
(int
)seq.
size()
;j++)if
(seq[i]
>seq[j]
) cnt++;if
(cnt&
1) cout<<
"unsolvable"
reverse
(res.
begin()
,res.
end())
; cout<}}
八數碼(IDA 演算法)
八數碼 ida 就是迭代加深和a 估價的結合 在迭代加深的過程中,用估計函式剪枝優化 並以比較優秀的順序進行擴充套件,保證最早搜到最優解 需要空間比較小,有時跑得比a 還要快 include include include include include using namespace std in...
八數碼寬度優先演算法
相關 要感謝網上的一些大神給予的分享 用來作為乙個結點的資料結構。struct map 用來列印乙個結點 cout函式用來擴充套件乙個結點的後繼結點 上 下 左 右 if hasgetblankcell break 移動數字,t i,t j為移動後0的座標 int t i i,t j j bool ...
acwing 845 八數碼 (最小步數模型)
我們可以將這個問題抽象成乙個圖。設原始狀態為起點,結尾狀態為終點,變化的狀態為中間點,每次都可以將x位置與它相鄰的四個方向交換 4中狀態,符合條件下 這四個方向的狀態就是新的點,而且是這個狀態能到達的點,我們設點之間的距離是1,那麼要求的變換最少次數就是求起始點到終點的最短距離 我們將起始點放入bf...