一只小蒟蒻备考蓝桥杯的日志
文章目录
笔记
遍历 (DFS主题)
参考 BFS 的使用场景:层序遍历、最短路径问题
DFS -> 层次遍历 -> 无权图的最短路径 (Dijkstra 算法平替)
实现:
用队列存储, 出队, 孩子进队
隐式图遍历:
华容道, 出发点是空的那个位置, 真难想到
#include <stdio.h>
#include <iostream>
#include <queue>
#include <map>
using namespace std;
int mov[4][3] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
// right down left up
map<string, int> dist;
int main() {
string str1;
string str2;
getline(cin, str1);
getline(cin, str2);
string str = str1 + str2;
int A = str.find('A');
int B = str.find('B');
queue<string> q;
q.push(str);
int ans;
dist[str] = 0;
while(q.empty() == false){
string tmp = q.front();
q.pop();
// cout << tmp << endl;
if(A == tmp.find('B') && B == tmp.find('A')) {
ans = dist[tmp];
break;
}
int index = tmp.find(' ');
int x = index % 3;
int y = index / 3;
int distance = dist[tmp];
for(int i = 0; i < 4; i++) {
int x1 = x + mov[i][0];
int y1 = y + mov[i][1];
if(x1 < 0 || x1 > 2 || y1 < 0 || y1 > 1) {
continue;
}
int xy2_1 = y1 * 3 + x1;
swap(tmp[xy2_1], tmp[index]);
if(dist.count(tmp) == 0) { //not exist
q.push(tmp);
dist[tmp] = distance + 1;
}
// cout << "swap: " << tmp << endl;
swap(tmp[xy2_1], tmp[index]);
}
}
cout << ans << endl;
return 0;
}
刷题
心得
- 第1题, 挺好的, 学到很多
-
队列的运用queue, q.front(), q.pop(), q.push()
-
是否走过该位置, 那个二维换成一维比对的方法很巧,
if(dist.count(tmp) == 0) //not existint x = index % 3;
int y = index / 3;
int xy2_1 = y1 * 3 + x1; //二维->一维 -
map的运用, map<string, int> dist;
-
上下左右移位, 原来可以通过存一个数组, 遍历实现, int mov[4][3] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
-
建议背诵笔记第一点demo, 因为小蒟蒻一边一定记不住这些用法
-
小结
为什么省赛日志没有 [5/37] 呢,因为昨天没准备…标题其实是倒计时…
好heartbroken的一天,很疲惫,但很失意和徒劳无获,可能是前端吧…
又水了一篇,水了一天
“聪明的,你告诉我,为什么我们的日子一去不复返了呢?”
“业精于勤荒于嬉,行成于思毁于随”
小蒟蒻一个月,冲省一!