当前位置:网站首页>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
边栏推荐
- MySQL time function query
- Simply drag objects to the item bar
- The programmer starts the required application with one click of window bat
- Sword finger offer: the median in the data stream (priority queue large top heap small top heap leetcode 295)
- Leetcode006 -- find the longest common prefix in the string array
- Programmers complain: I really can't live with a salary of 12000. Netizen: how can I say 3000
- leetcode009--用二分查找在数组中搜索目标值
- PIP3 installation requests Library - the most complete pit sorting
- L2-011 玩转二叉树(建树+BFS)
- Innovation training (V) mid term inspection
猜你喜欢

Flink's important basics

What is a data island? Why is there still a data island in 2022?

Innovation training (V) configuration information

Youqilin 22.04 lts version officially released | ukui 3.1 opens a new experience

Spark optimization

Customize the navigation bar at the top of wechat applet (adaptive wechat capsule button, flex layout)
![[timing] empirical evaluation of general convolution and cyclic networks for sequence modeling based on TCN](/img/c5/3b3f9cf9a39bf14a68ac100294ca6c.png)
[timing] empirical evaluation of general convolution and cyclic networks for sequence modeling based on TCN

Druid -- JDBC tool class case

Painless upgrade of pixel series

The 14th issue of HMS core discovery reviews the long article | enjoy the silky clip and release the creativity of the video
随机推荐
What is the meaning of load balancing
leetcode009--用二分查找在数组中搜索目标值
Leetcode009 -- search the target value in the array with binary search
Arduino UNO r3+LCD1602+DHT11
POI export message list (including pictures)
Wine (COM) - basic concept
leetcode008--实现strStr()函数
Unity摄像头跟随鼠标旋转
Learning Android from scratch -- baseactivity and activitycollector
Learning Android V from scratch - UI
Wechat payment function
Summary of MySQL de duplication methods
C list field sorting contains numbers and characters
IEEE Transactions on systems, man, and Cybernetics: Notes for systems (TSMC)
持续集成(CI)/持续交付(CD)如何彻底改变自动化测试
leetcode005--原地删除数组中的重复元素
Solutions to the failure of sqoop connection to MySQL
Innovation training (IV) preliminary preparation - server
Unity camera rotation with sliding effect (rotation)
js 判断数字字符串中是否含有字符