题目链接:http://lx.lanqiao.cn/problem.page?gpid=T448
bfs题目,套模板即可详细可看bfs见解和模板。
要点:
我们读题可以知道:空少青蛙多,如果我们遍历每只青蛙能否进洞,应该超时。
虽然我们应该遍历洞,看这个洞哪些青蛙可以进。
#include <iostream>
#include <cstdio>
#include <map>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <cstring>
#include <cmath>
#include <stack>
#include <queue>
#include <set>
#include <iomanip>
using namespace std;
int dir[6] = {-3, -2, -1, 1, 2, 3};
set<string> vis;
string beg, ed;
struct Node {
string str;
int dist;
Node(string s, int d):
str(s), dist(d) {}
};
void bfs() {
queue<Node> queue;
queue.push(Node(beg, 0));
while(!queue.empty()) {
Node u = queue.front(); queue.pop();
string sstr = u.str;
int len = sstr.size();
if(sstr == ed) {
cout << u.dist << endl;
return;
}
// 寻找每个空,看看哪些青蛙可以跳进这些空
for(int i = 0; i < len; i++) {
if(sstr[i] == '*') {
for(int j = 0; j < 6; j++) {
// 这些位置的青蛙可以进
int p_t = i + dir[j];
string str_t = sstr;
if(p_t>=0 && p_t<len && sstr[p_t]!='*') {
// 跳进去 青蛙位置变为空*
str_t[i] = str_t[p_t];
str_t[p_t] = '*';
// 查重
if(!vis.count(str_t)) {
queue.push(Node(str_t, u.dist+1));
vis.insert(str_t);
}
}
}
}
}
}
}
int main() {
// freopen("i.txt", "r", stdin);
// freopen("o.txt", "w", stdout);
cin >> beg >> ed;
bfs();
return 0;
}