思路
- 这一题我们用bfs来搜索每一条路径,对与正在搜素的某个路径的下一个节点位置我们怎么判断它是否已经走过了?,这做的思路就是对每个节点 我们都给 加一个 vector road; 去存储路径,如果路径road中已经有这个节点那么表 这个节点已经走过了,那么这条路径就重复了,就不要把这个路径压入到 队列q 中了,,,,还有一下剪枝、细节直接看代码吧
代码
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
#include<map>
#include<string>
#include<cstdio>
#include<cmath>
#include<stack>
void fre() { freopen("A.txt", "r", stdin); freopen("Ans.txt","w",stdout); } void Fre() { freopen("A.txt", "r", stdin);}
#define ios ios::sync_with_stdio(false)
#define Pi acos(-1)
#define pb push_back
#define fi first
#define se second
#define ll long long
#define ull unsigned long long
#define db double
#define Pir pair<int, int>
#define PIR pair<Pir, Pir>
#define m_p make_pair
#define INF 0x3f3f3f3f
#define mod (ll)(1e9 + 7)
#define for_(i, s, e) for(int i = (s); i <= (e); i ++)
#define rep_(i, e, s) for(int i = (e); i >= (s); i --)
#define sd(a) scanf("%d", &a)
#define sc(a) scanf("%c", &a)
using namespace std;
const int mxn = 1e6;
int mz[25][5];
struct Node
{
int p;
vector<int> road;
};
void bfs(int s)
{
Node u((Node){ s });
queue<Node> q;
q.push(u);
int Case = 1;
while(! q.empty())
{
u = q.front(); q.pop();
if(u.road.size() == 20 && u.road[u.road.size() - 1] == s)
{
printf("%d: %d", Case ++, s);
for(auto x : u.road)
printf(" %d", x);
printf("\n");
}
if(u.road.size() && u.road[u.road.size() - 1] == s) continue;
for_(i, 1, 3)
{
if(find(u.road.begin(), u.road.end(), mz[u.p][i]) != u.road.end()) continue;
Node v((Node){ mz[u.p][i], u.road });
v.road.pb(mz[u.p][i]);
q.push(v);
}
}
}
int main()
{
for_(i, 1, 20)
scanf("%d %d %d", &mz[i][1], &mz[i][2], &mz[i][3]);
int s;
while(sd(s) && s)
bfs(s);
return 0;
}