跳蚱蜢问题

编程入门 行业动态 更新时间:2024-10-11 03:21:52

跳<a href=https://www.elefans.com/category/jswz/34/1760569.html style=蚱蜢问题"/>

跳蚱蜢问题

#include<bits/stdc++.h>
using namespace std;
string st = "123456780", ed = "876543210";
int dx[] = {1,-1,2,-2};
int n = 9;int bfs(){unordered_map <string, int> dist; // dist[str] 存的是 从st到str的最短距离dist[st] = 0;queue<string> q;q.push(st);while(q.size()){//auto 自动识别类型//front拿到队列组前面的元素 auto t = q.front(); //可以发现这里t为string类型 q.pop();//k空盘的位置 int k = t.find('0');//遍历四个方向 for(int i = 0; i < 4; i++){string str = t;swap(str[k],str[(k + dx[i] + n) % n]);if(dist.count(str)) continue;dist[str] = dist[t] + 1;if(str==ed) return dist[str];q.push(str);} }return -1 ;
} int main(){cout<<bfs()<<endl;return 0;
}

 

更多推荐

跳蚱蜢问题

本文发布于:2024-02-13 20:59:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1760260.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:蚱蜢

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!