目录
搜索问题
深度优先搜索
翻转开关问题
迭代加深搜索
埃及分数问题
广度优先搜索
双向广度优先搜索
八数码问题
#include <iostream>
#include <string>
#include <queue>
#include <map>
using namespace std;
//记录该string状态处于正(反)向的第几层BFS
map<string, int>fsign, rsign;
int fcnt[300000];
int rcnt[300000];
string aim = "123804765";
//1:up,2:down,3:left,4:right
int moveto(int i, int index) {
switch (i) {
case 1:
if (index - 3 >= 0)return index - 3;
break;
case 2:
if (index + 3 <= 8)return index + 3;
break;
case 3:
if (index % 3 != 0)return index - 1;
break;
case 4:
if (index % 3 != 2)return index + 1;
break;
}
return -1;
}
bool extend(queue<string>&q, int head, int &tail, int direction) {
string now = q.front(); q.pop();
int from = now.find('0');
for (int i = 1; i <= 4; i++) {
int to = moveto(i, from);
if (to != -1) {
swap(now[from], now[to]);
if (direction == 1) { //up to dowm
if (!fsign[now]) { // not visited yet
q.push(now);
fsign[now] = fcnt[tail++] = fcnt[head] + 1;
if (rsign[now]) {
cout << fcnt[tail - 1] + rsign[now] << endl;
return true;
}
}
}
else {// down to up
if (!rsign[now]) {
q.push(now);
rsign[now] = rcnt[tail++] = rcnt[head] + 1;
if (fsign[now]) {
cout << rcnt[tail - 1] + fsign[now] << endl;
return true;
}
}
}
swap(now[from], now[to]);
}
}
return false;
}
void DBFS(string start) {
if (start.compare(aim) == 0) {
cout << '0' << endl;
return;
}
bool flag = false;
queue<string>forward, reverse;
forward.push(start);
reverse.push(aim);
string forwardNow = start, reverseNow = aim;
fsign[start] = 0; rsign[aim] = 0;
int head = 0, tail = 1, rhead = 0, rtail = 1;
while (!flag) {
if (forward.size() <= reverse.size()) { // choose the shorter one
if (extend(forward, head, tail, 1))return;
head++;
}
else {
if (extend(reverse, rhead, rtail, 2))return;
rhead++;
}
}
}
int main() {
string start;
cin >> start;
DBFS(start);
return 0;
}
动态规划
一维递推问题(求和形式)
爬楼梯
一维递推问题(最值形式)
数字三角形
动态规划详解(数字三角形POJ1163)_ancientear的博客-CSDN博客_数字三角形动态规划