当前位置:网站首页>Leetcode -- heuristic search
Leetcode -- heuristic search
2022-04-23 04:50:00 【csdn_ ggboy】
847. The shortest path to access all nodes - Power button (LeetCode)
A very important optimization , The starting point must be the one with the least number of connecting nodes , This ensures the shortest path
class Solution
{
public:
struct state
{
int now;
int loc;
int dist; // This is more useful dist,dis + astar
// The return value is bool type , Overload operator <, The parameter on the right is the reference that cannot be modified , This function does not modify the value of the structure
bool operator<(const state &rhs) const
{
return dist > rhs.dist;
}
};
int astar(int loc)
{
// 1 The number of points indicates which points to go
int res = 0;
while (loc)
{
loc -= (loc & -loc);
res++;
}
return res;
}
int shortestPathLength(vector<vector<int>> &graph)
{
int n = graph.size();
int ans = 0x3f3f3f3f;
int mi = 0x3f3f3f3f;
for(auto &p: graph)
mi=min(mi, (int)p.size());
unordered_map<int, unordered_map<int, int>> dist;
priority_queue<state, vector<state>> q;
for (int i = 0; i < n; i++)
{
// The starting point i
if(graph[i].size() != mi) continue;
int loc = ((1 << n) - 1) ^ (1 << i);
dist[i][loc] = 0;
q.push({
i, loc, n - 1});
}
while (q.size())
{
auto t = q.top();
q.pop();
int u = t.now;
int d = astar(t.loc);
if(d > astar(t.loc) + dist[u][t.loc]) continue;
if (astar(t.loc) == 0)
{
ans = min(ans, t.dist);
break;
}
for (int j = 0; j < graph[u].size(); j++)
{
int nx = graph[u][j];
int nloc = t.loc;
if (t.loc & (1 << nx))
nloc ^= (1 << nx);
// If nx The position has not passed , to update nloc
// if(st[nx][nloc]) continue;
if (!dist.count(nx) || !dist[nx].count(t.loc) || dist[nx][nloc] > dist[u][t.loc] + 1)
{
dist[nx][nloc] = dist[u][t.loc] + 1;
q.push({
nx, nloc, dist[nx][nloc] + astar(nloc)});
}
}
}
return ans;
}
};
127. The word chain - Power button (LeetCode)
class Solution
{
public:
typedef pair<int,int> PII;
bool edgeif(string a, string b)
{
unordered_map<char, int> mp;
if (a == b)
return true;
bool flag = false;
for (int i = 0; i < a.size(); i++)
{
if (a[i] != b[i] && !flag)
{
flag = true;
}
else if(a[i] != b[i] && flag)
return false;
}
return true;
}
int astar(int _a, int _end, vector<string> &wordList)
{
string a = wordList[_a];
string end = wordList[_end];
if (a.size() != end.size())
return 0x3f3f3f3f;
int res = 0;
for (int i = 0; i < a.size(); i++)
{
if (a[i] != end[i])
res++;
}
return res;
}
int ladderLength(string beginWord, string endWord, vector<string> &wordList)
{
wordList.push_back(beginWord);
if (find(wordList.begin(), wordList.end(), endWord) == wordList.end())
return 0;
wordList.push_back(endWord);
int n = wordList.size();
unordered_map<string, int> mp;
for(int i = 0; i < wordList.size(); i ++) mp[wordList[i]] = i;
int dist[n];
bool st[n];
memset(dist, 0x3f3f3f3f, sizeof(dist));
memset(st, 0, sizeof(st));
dist[n - 2] = 0;
st[n - 2] = true;
priority_queue<PII, vector<PII>, greater<PII>> q;
q.push({
astar(n - 2, n - 1, wordList), n - 2});
while (q.size())
{
auto t = q.top();
q.pop();
int u = t.second;
if(u == n - 1) break;
st[u] = false;
for(int i = 0; i < 26; i ++ )
for(int j = 0; j < wordList[u].size(); j ++)
{
string now = wordList[u];
if(now[j] != 'a' + i)
{
now[j] = 'a' + i;
}
if(!mp.count(now))
continue;
int to = mp[now];
if (st[to])
continue;
int d_a = astar(to, n - 1, wordList);
if (dist[to] > dist[u] + 1 )
{
dist[to] = dist[u] + 1;
st[to] = true;
q.push({
dist[to] + d_a, to});
}
}
}
if (dist[n - 1] >= 0x3f3f3f3f)
return 0;
return dist[n - 1] + 1;
}
};
752. Open the turntable lock - Power button (LeetCode)
class Solution
{
public:
// 0 1 2 3 4 5 6 7 8 9
typedef pair<int, string> PIS;
int astar(string a, string target)
{
int res = 0;
for (int i = 0; i < a.size(); i++)
{
res += min((a[i] - target[i] + 10) % 10, (-a[i] + target[i] + 10) % 10);
}
return res;
}
int openLock(vector<string> &deadends, string target)
{
if(target == "0000") return 0;
// Each number can have two rotation modes , You can choose one position at a time to rotate , Can't rotate to death number
priority_queue<PIS, vector<PIS>, greater<PIS>> q;
unordered_map<string, bool> st;
unordered_map<string, int> dist;
for (auto p : deadends)
st[p] = true; // Mark death status
if (!st["0000"])
{
q.push({
astar("0000", target), "0000"}); // The initial state
st["0000"] = true;
}
bool flag = false;
while (!q.empty())
{
auto u = q.top();
string t = u.second;
st[t] = false;
q.pop();
if (t == target)
{
break;
}
for (int i = 0; i < 4; i++) // Find a place
{
string ne = t;
ne[i] = (t[i] - '0' + 1) % 10 + '0';
if (!st[ne])
{
if (!dist.count(ne) || dist[ne] > dist[t] + 1)
{
dist[ne] = dist[t] + 1;
st[ne] = true;
q.push({
dist[ne] + astar(ne, target), ne});
}
}
ne[i] = (t[i] - '0' - 1 + 10) % 10 + '0';
if (!st[ne])
{
if (!dist.count(ne) || dist[ne] > dist[t] + 1)
{
dist[ne] = dist[t] + 1;
st[ne] = true;
q.push({
dist[ne] + astar(ne, target), ne});
}
}
}
}
if (dist.count(target))
return dist[target];
else
return -1;
}
};
773. Slide Puzzle - Power button (LeetCode)
#define x first
#define y second
class Solution {
public:
string end = "123450";
int dx[4] = {
0, 0, 1, -1}, dy[4] = {
1, -1, 0, 0};
typedef pair<int, string> PIS;
int f(string s)
{
int res = 0;
for(int i = 0; i < s.size(); i ++ )
if(s[i] != '0')
{
int p = s[i] - '1';
res += abs(i / 3 - p / 3) + abs(i % 3 - p % 3);
}
return res;
}
int bfs(string state)
{
unordered_map <string, int> dist;
priority_queue <PIS, vector<PIS>, greater<PIS>> q;
unordered_map <string, bool> st;
st[state] = true;
q.push({
f(state), state});// Put the initial state on the stack
dist[state] = 0;
while(q.size())
{
auto t = q.top();
q.pop();
string s = t.y;
if(s == end) break;
st[s] = false;
int x, y;
for(int i = 0; i < 6; i ++ )// find 0 The location of
{
if(s[i] == '0')
{
x = i / 3;
y = i % 3;
break;
}
}
for(int i = 0; i < 4; i ++ )// And up, down, left and right
{
int nx = x + dx[i], ny = y + dy[i];
if(nx < 0 || ny < 0 || nx > 1 || ny > 2) continue;// Two lines and three columns
string source = s;
swap(source[x * 3 + y], source[nx * 3 + ny]);
if(st[source]) continue;
if(!dist.count(source) || dist[source] > dist[s] + 1)//dist Is it infinity or is it greater than s + 1 Big
{
dist[source] = dist[s] + 1;
q.push({
f(source) + dist[source], source});
}
}
}
return dist[end];
}
int slidingPuzzle(vector<vector<int>>& board) {
//A* Stack multiple times , The end point stack can only determine the shortest path of the end point
// Judge whether there is a solution
string start;
for(auto &t : board)
for(auto &x : t)
start += x + '0';
int cnt = 0;
for(int i = 0; i < 6; i ++ )
for(int j = i + 1; j < 6; j ++ )
{
if(start[i] != '0' && start[j] != '0' && start[j] < start[i]) cnt ++;
}
if(cnt % 2) return -1;
else return bfs(start);
}
};
版权声明
本文为[csdn_ ggboy]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230449324968.html
边栏推荐
- Record the blind injection script
- Introduction to raspberry pie 3B - system installation
- JS détermine si la chaîne de nombres contient des caractères
- Excel protects worksheets and workbooks from damage
- Practice and exploration of knowledge map visualization technology in meituan
- Eight misunderstandings that should be avoided in data visualization
- PIP3 installation requests Library - the most complete pit sorting
- Spark small case - RDD, broadcast
- redis数据类型有哪些
- Solutions to the failure of sqoop connection to MySQL
猜你喜欢
简单的拖拽物体到物品栏
Programmers complain: I really can't live with a salary of 12000. Netizen: how can I say 3000
Mysql50 basic exercises
Installation and deployment of Flink and wordcount test
【数据库】表的查看、修改和删除
New terminal play method: script guidance independent of technology stack
Painless upgrade of pixel series
Spark small case - RDD, spark SQL
Recommended scheme for national production of electronic components of wireless keyboard
Recommended scheme for national production of electronic components for wireless charging
随机推荐
Custom switch control
The object needs to add additional attributes. There is no need to add attributes in the entity. The required information is returned
Sword finger offer: the path with a certain value in the binary tree (backtracking)
做数据可视化应该避免的8个误区
程序员抱怨:1万2的工资我真的活不下去了,网友:我3千咋说
Detailed explanation of the differences between TCP and UDP
leetcode——启发式搜索
JS determines whether the numeric string contains characters
List remove an element
Leetcode005 -- delete duplicate elements in the array in place
Learning Android from scratch -- baseactivity and activitycollector
Raspberry pie + opencv + opencv -- face detection ------- environment construction
Recommended scheme of national manufactured electronic components for intelligent electronic scales
MySQL - data read / write separation, multi instance
unity摄像机旋转带有滑动效果(自转)
Download PDF from HowNet (I don't want to use CAJViewer anymore!!!)
leetcode004--罗马数字转整数
Innovation training (V) mid term inspection
Solutions to the failure of sqoop connection to MySQL
Improving 3D object detection with channel wise transformer