当前位置:网站首页>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
边栏推荐
- /etc/bash_ completion. D directory function (the user logs in and executes the script under the directory immediately)
- Use model load_ state_ Attributeerror appears when dict(): 'STR' object has no attribute 'copy‘
- PHP 统计指定文件夹下文件的数量
- What's the difference between error and exception
- What is a data island? Why is there still a data island in 2022?
- Spark FAQ sorting - must see before interview
- Spell it! Two A-level universities and six B-level universities have abolished master's degree programs in software engineering!
- Installation and deployment of Flink and wordcount test
- Analysis of POM files
- Case of using stream load to write data to Doris
猜你喜欢
简单的拖拽物体到物品栏
使用model.load_state_dict()时,出现AttributeError: ‘str‘ object has no attribute ‘copy‘
Spark FAQ sorting - must see before interview
Improving 3D object detection with channel wise transformer
Sword finger offer: the path with a certain value in the binary tree (backtracking)
Detailed explanation of the differences between TCP and UDP
Innovation training (IV) preliminary preparation - server
Learning Android II from scratch - activity
Innovation training (V) configuration information
Spark small case - RDD, spark SQL
随机推荐
Practice and exploration of knowledge map visualization technology in meituan
L2-011 玩转二叉树(建树+BFS)
泰克示波器DPO3054自校准SPC失败维修
Sword finger offer: symmetric binary tree (recursive iteration leetcode 101)
Progress of innovation training (III)
简单的拖拽物体到物品栏
FAQ of foreign lead and alliance Manager
Wechat payment function
Code007 -- determine whether the string in parentheses matches
Installation and deployment of Flink and wordcount test
Innovation training (V) mid term inspection
Leetcode002 -- inverts the numeric portion of a signed integer
Recommended scheme of national manufactured electronic components for intelligent electronic scales
redis和mysql区别
MySQL - index
Use model load_ state_ Attributeerror appears when dict(): 'STR' object has no attribute 'copy‘
Open the past and let's start over.
MySQL - data read / write separation, multi instance
AQS源码阅读
redis数据类型有哪些