[蓝桥杯2017初赛]跳蚱蜢-map标记+bfs+环形数组
生活随笔
收集整理的這篇文章主要介紹了
[蓝桥杯2017初赛]跳蚱蜢-map标记+bfs+环形数组
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
解題思路:
這題如果我們考慮蚱蜢跳,有很多蚱蜢,有很多情況,所以我們讓空盤跳,這樣就簡化題目了,然后我們化圓為直,將題目的情況看成字符串012345678,最后要變成087654321,這樣題目就變得跟[藍橋杯2017初賽]青蛙跳杯子
一樣了,唯一的區(qū)別就是這個是個圓,所以在012345678這個字符串中,0往左跳會跳到8的位置,故需要用環(huán)形數(shù)組,我們用map存儲字符串來標記。
關鍵點:
1.關于環(huán)形的數(shù)組,前移動和后移動可能會溢出下標。解決方法是,轉移后的坐標公式為
(原坐標+改變量+數(shù)組長度)%數(shù)組長度
2.map標記,圓盤在跳。
代碼如下:
#include <iostream> #include <queue> #include <map> #include <cstring> using namespace std; string a, b; int len; int dian;//(原坐標+改變量+數(shù)組長度)%數(shù)組長度 int dx[] = {1, -1, 2, -2};struct node {string str;int dian;int step;node(string str1, int dian1, int step1) {str = str1;dian = dian1;step = step1;} };int bfs() {map<string, int> st;queue<node>q;q.push(node(a, dian, 0));st[a] = 1;while (q.size()) {node t = q.front();q.pop();if (t.str == b) {return t.step;}for (int i = 0; i < 4; i++) {int dianf = (t.dian + dx[i] + len) % len;//環(huán)形數(shù)組if (dianf < 0 || dianf >= len)continue;string strf = t.str;char hhh = strf[t.dian];strf[t.dian] = strf[dianf];strf[dianf] = hhh;if (st.count(strf) == 0) {q.push(node(strf, dianf, t.step + 1));st[strf] = 1;}}}}int main() {a = "012345678";b = "087654321";len = a.length();dian = 0;//0在a中的位置cout << bfs() << endl;return 0; } #include <iostream> #include <queue> #include <cstring> #include <map> using namespace std; string a = "012345678"; string b = "087654321";struct node {string s;int dian;int p; };int dx[] = {1, -1, 2, -2};void bfs(node start) {queue<node>q;map<string, int>mp;q.push(start);mp[start.s] = 1;while (q.size()) {node t = q.front();q.pop();if (t.s == b) {cout << t.p << endl;return ;}for (int i = 0; i < 4; i++) {int dians = (t.dian + dx[i] + 9) % 9;if (dians < 0 || dians >= 9 )continue;string ss = t.s;char hh = ss[t.dian];ss[t.dian] = ss[dians];ss[dians] = hh;if (mp.count(ss) == 0) {mp[ss]= 1;q.push({ss, dians, t.p + 1});}}} }int main() {node start = {a, 0, 0};bfs(start);return 0; }總結
以上是生活随笔為你收集整理的[蓝桥杯2017初赛]跳蚱蜢-map标记+bfs+环形数组的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 创维汽车首款轿车 SKYHOME 首发亮
- 下一篇: Meta 展示全新 AI 图像编辑工具: