萌新 刚学oi 双向bfs 求助((
查看原帖
萌新 刚学oi 双向bfs 求助((
150467
never_turn_right楼主2021/3/2 16:49
#include<bits/stdc++.h>
using namespace std;
string mb="111110111100*110000100000";
string s,ssr;
int T;
int mv[8][2]={{-2,-1},{-1,-2},{1,-2},{2,-1},{2,1},{1,2},{-1,2},{-2,1}};
struct node
{
	string str;int stp,x,y;
	node(string _str,int _stp,int _x,int _y)
	{
		str=_str;
		stp=_stp;
		x=_x;
		y=_y;
	}
};
int main()
{
	cin>>T;
	while(T--)
	{
		map<string,int> mp;

		s.clear();
		for(int i=1;i<=5;i++)
		{
			cin>>ssr;
			s+=ssr;
		}
		int xx,yy;
		for(int i=0;i<=24;i++)
		{
			if(s[i]=='*') {xx=(i+1)/5+1; yy=(i+1)%5;}
		}
		queue<node> q1;
		q1.push(node(s,0,xx,yy));
		while(q1.size()!=0)
		{
			node nop=q1.front();
			q1.pop();
			if(nop.str==mb)
			{
				//cout<<nop.stp<<endl;
				break;
			}
			if(nop.stp>=8)
			{
				break;				
			}
			for(int i=0;i<8;i++)
			{
				int nox=nop.x+mv[i][0];
				int noy=nop.y+mv[i][1];
				if(nox>0&&nox<=5&&noy>0&&noy<=5)
				{
					string stt=nop.str;
					swap(stt[nop.x*5-5+nop.y-1],stt[nox*5-5+noy-1]);
					//cout<<nop.str<<endl;
					//if(nop.str=="111110001000111*011100000") cout<<"2q32343425";
					if(mp[stt]==0)
					{
						mp[stt]=mp[nop.str]+1;
						q1.push(node(stt,nop.stp+1,nox,noy));
					}
				}	
			}
		}
		queue<node> q2;
		map<string,int> mp2;
		q2.push(node(mb,0,3,3));
		int ans=0x7fffffff;
		while(q2.size()!=0)
		{
			node nop=q2.front();
			q2.pop();
			if(mp[nop.str]!=0)
			{                                                                  
				cout<<nop.stp+mp[nop.str]<<endl;
				break;
			}
			if(nop.stp>=9) 
			{
				cout<<"-1"<<endl;
				break;				
			}
			for(int i=0;i<8;i++)
			{
				int nox=nop.x+mv[i][0];
				int noy=nop.y+mv[i][1];
				if(nox>0&&nox<=5&&noy>0&&noy<=5)
				{
					string stt=nop.str;
					swap(stt[nop.x*5-5+nop.y-1],stt[nox*5-5+noy-1]);
					//cout<<nop.str<<endl;
					//if(nop.str=="111110001000111*011100000") cout<<"2q32343425";
					if(mp2[stt]==0)
					{
						mp2[stt]=mp2[nop.str]+1;
						q2.push(node(stt,nop.stp+1,nox,noy));
					}
				}	
			}
		}
	}
	return 0;
}


这个点老是过不去

//输入
5
01111
00010
1111*
00111
00000
*1011
11101
01011
00101
00000
10111
00111
*1111
00001
00000
011*1
00101
10111
10001
00100
11011
01100
00100
01*11
01100
//答案
14
8
8
13
-1
//我的答案
16
8
8
13
-1

谢谢各位大佬

2021/3/2 16:49
加载中...