启发式搜索A* 算法
最编程
2024-03-22 09:39:01
...
class Solution {
public:
int slidingPuzzle(vector<vector<int>>& board) {
string start = zip(board);
string target = zip({{1, 2, 3}, {4, 5, 0}});
//q.push(start);
q.push({-evaluate(start), start});
depth[start] = 0;
while (!q.empty()) {
string s = q.top().second;
q.pop();
int pos = findZeroIndex(s);
if (pos >= 3) expand(s, pos, pos - 3);
if (pos <= 2) expand(s, pos, pos + 3);
if (pos % 3 != 0) expand(s, pos, pos - 1);
if (pos % 3 != 2) expand(s, pos, pos + 1);
if (depth.find(target) != depth.end()) return depth[target];
}
return -1;
}
private:
int evaluate(string &s) {
int now[6];
for (int i = 0; i < 6; i++) {
if (s[i] != '0')
now[s[i] - '0'] = i;
}
int target[6] = {0 ,0 ,1, 2, 3, 4};
int ans = 0;
for (int digit = 1; digit <= 5; digit++) {
int nowx = now[digit] / 3;
int nowy = now[digit] % 3;
int targetx = target[digit] / 3;
int targety = target[digit] % 3;
ans += abs(nowx - targetx) + abs(nowy - targety);
}
return ans;
}
void expand(string& s, int pos, int other) {
string ns = s;
swap(ns[pos] , ns[other]);
if (depth.find(ns) != depth.end()) return;
depth[ns] = depth[s] + 1;
q.push({ - depth[ns] - evaluate(ns), ns});
//q.push(ns);
}
string zip(const vector<vector<int>>& board) {
string res;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
res += '0' + board[i][j];
}
}
return res;
}
int findZeroIndex(string& s) {
for (int i = 0; i < 6; i++) if (s[i] == '0') return i;
return -1;
}
//queue<string> q;
priority_queue<pair<int, string>> q;
unordered_map<string, int> depth;
};
推荐阅读
-
基于深度学习的 3D 重建算法综述
-
三维重建算法概述 | 传统 + 深度学习
-
基于可视化船体算法的图像三维重建 matlab 仿真
-
MATLAB 入门 (22) - 哈希算法
-
Mahout-Collaborative-Filtering-CF-Recommendation 算法的基本概念和代码示例
-
TDOA 定位] 基于 chan 和 talor 算法的 TDOA 定位及性能比较 matlab 代码
-
路径规划 - 搜索算法详解 (III):用 MATLAB 代码解释 RRT 算法
-
[C++][算法基础]不相交区间的最大数目(贪婪 +区间问题 2)
-
从表达谱数据推断基因调控网络的 ARACNE 算法
-
WSN 定位]基于chan算法的多基站目标定位(附Matlab代码