双向bfs-八数码问题

[八数码][1]
[1]: https://www.luogu.org/problem/show?pid=1379
其实除了搜索恶心一点,好像也没什么提高+的
bfs搜的是状态。
双向bfs同时从起点(初始状态)和终点(最终状态)开始搜。当两边搜到同样的状态说明出结果了。因为bfs是一层层搜的,所以最早搜到同样状态就是最优解。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<ctime>
#include<string>
#include<set>
#include<queue>
#include<vector>
using namespace std;
struct str
{
	string s;//当前状态字符串
	int posi;//当前状态0的位置
};
int fangxiang[]={-3,+1,+3,-1};//up right down left
//fangxiang[]预先储存好各个方向的运算数,直接把0的位置加上去就好
set <string> m1,m2;//set判断这个状态是否已经有了
queue <str> q1,q2;//queue是枚举的状态
int c,c1=1,c2=1,cc;//c为循环边界(由c1,c2)获得,c1是上次bfs得来的本次bfs的状态数
int bfs()
{
	while(!q1.empty())
	{
		cc++;
		str t,x;
		//zheng
		c=c1;
		c1=0;
		while(c--)
		{
			t=q1.front();
			q1.pop();
			for(int j=0;j<4;j++)
			{
				x=t;
				//看下面,都差不多的
				if(j==0 and t.posi<3)
					continue;
				if(j==1 and t.posi%3==2)
					continue;
				if(j==2 and t.posi>5)
					continue;
				if(j==3 and t.posi%3==0)
					continue;
				swap(x.s[x.posi],x.s[x.posi+fangxiang[j]]);
				x.posi+=fangxiang[j];
				if(m1.count(x.s))
					continue;
				q1.push(x);
				c1++;
				m1.insert(x.s);
				if(m2.count(x.s))
					return cc*2-1;
			}
		}
		//fan
		c=c2;
		c2=0;
		for(int i=0;i<c;i++)
		{
			t=q2.front();//取出队首,进行bfs
			q2.pop();
			for(int j=0;j<4;j++)
			{
				x=t;
				//需要枚举4个方向,所以用个x
				if(j==0 and t.posi<3)
					continue;
				if(j==1 and t.posi%3==2)
					continue;
				if(j==2 and t.posi>5)
					continue;
				if(j==3 and t.posi%3==0)
					continue;
				//限制条件
				swap(x.s[x.posi],x.s[x.posi+fangxiang[j]]);//移动0
				x.posi+=fangxiang[j];
				if(m2.count(x.s))
					continue;
				q2.push(x);
				c2++;
				m2.insert(x.s);
				if(m1.count(x.s))
					return cc*2;
			}
		}
	}
	return 0;
}
int main()
{
    //freopen("4.in","r",stdin);
	ios::sync_with_stdio(false);
	str ed=(str){"123804765",4};
	str st;
	cin>>st.s;
	st.posi=st.s.find('0');
	q1.push(st);
	q2.push(ed);
	m1.insert(st.s);
	m2.insert(ed.s);
	if(st.s==ed.s)//如果起始和终止相同,那太好了根本不用移!
	{
		cout<<"0";
		return 0;
	}
	cout<<bfs();
	return 0;
}
原文地址:https://www.cnblogs.com/syhien/p/7727621.html