1318: [蓝桥杯2017初赛]跳蚱蜢 【中 / bfs】

在这里插入图片描述
http://oj.ecustacm.cn/problem.php?id=1318
在这里插入图片描述

#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<queue>
#include<map>
using namespace std;
string s1="012345678";//当前状态
string s2="087654321";//最终状态
int dx[4]={1,2};//顺时针跳
int dy[4]={-1,-2};//逆时针跳
struct node
{
	int x;
	int step;
	string s;
}Node;
void bfs(int x)
{
	Node.x=0;
	Node.step=0;
	Node.s=s1;
	
	queue<node>q;
	q.push(Node);
	map<string,int>mp;
	mp[s1]=1; 
	while(!q.empty())
	{
		node top=q.front();
		q.pop();
		for(int i=0;i<2;i++)
		{
			int tempx=(top.x+dx[i])%9;
			string str=top.s;
			swap(str[top.x],str[tempx]);
			if(!mp[str])
			{
				node m;
				m.x=tempx;
				m.step=top.step+1;
				m.s=str;
				mp[str]=1;
				if(str==s2)
				{
					cout<<m.step<<endl; 
					return ;
				}
				q.push(m);
			}
		}
		for(int i=0;i<2;i++)
		{
			int tempx=top.x+dy[i]; 
			if(tempx==-1) tempx=8;
			if(tempx==-2) tempx=7;
			string str=top.s;
			swap(str[top.x],str[tempx]);
			if(!mp[str])
			{
				node m;
				m.x=tempx;
				m.step=top.step+1;
				m.s=str;
				mp[str]=1;
				if(str==s2)
				{
					cout<<m.step<<endl; 
				}
				q.push(m);
			}
		}
	}
}
int main(void)
{
	bfs(0);
	//cout<<20<<endl;
	return 0;
}

简写:

#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<queue> 
using namespace std;

string s="012345678";
string cmp="087654321";
int dx[4]={1,2,-1,-2};
struct node
{
	int x,step;
	string s;
}Node;
void bfs(int x)
{
	Node.x=x,Node.step=0,Node.s=s;
	queue<node>q;       q.push(Node);
	map<string,int>mp;  mp[s]=1;
	while(!q.empty())
	{
		node top=q.front();
		q.pop();
		for(int i=0;i<2;i++)
		{
			int tempx=(top.x+dx[i])%9;
			string ss=top.s;
			swap(ss[top.x],ss[tempx]);
			if(!mp[ss])
			{
				node m;
				m.x=tempx,	m.step=top.step+1;
				m.s=ss,		mp[ss]=1;
				if(ss==cmp)
				{
					cout<<m.step<<endl;
					return;
				}
				q.push(m);
			}
		}
		for(int i=0;i<2;i++)
		{
			int tempx=top.x+dx[i+2];
			if(tempx==-1) tempx=8;
			if(tempx==-2) tempx=7;
			string ss=top.s;
			swap(ss[top.x],ss[tempx]);
			if(!mp[ss])
			{
				node m;
				m.x=tempx, m.step=top.step+1;
				m.s=ss, mp[ss]=1;
				if(m.s==cmp)
				{
					cout<<m.step<<endl;
					return;
				}
				q.push(m);
			}
		}
	}
}

int main(void)
{
	bfs(0);
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值