蓝桥杯+BFS九宫格+了解了c++string compare()和c的string使用

点击打开链接
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string.h>
#include<cstring>
#include<string>
#include<math.h>
#include<algorithm>
#include<queue>
#include<set>
using namespace std;
struct Node{
	int x,y;
	int steps;
	string s;
};
const int dx[]={-1,1,0,0};
const int dy[]={0,0,-1,1};
queue<Node>Q;
set<string>vis;
string s1,s2;
void BFS()
{
	int i=0,z=0,x=0,y=0,newz=0;
	while(!Q.empty()) Q.pop();
	vis.clear();
	for(z=0;z<9;z++) if(s1[z]=='.') break;
	Node temp1,temp2;
	temp1.x=z/3;temp1.y=z%3;temp1.steps=0;temp1.s=s1;
	vis.insert(s1);
	Q.push(temp1);
	while(!Q.empty()){
		temp1=Q.front();Q.pop();
       /// cout<<temp1.s<<endl;
		if(temp1.s.compare(s2)==0){///c++中的字符串比较。
			printf("%d\n",temp1.steps);
			return;
		}
		for(i=0;i<4;i++){
			temp2=temp1;
			z=temp1.x*3+temp1.y;
			temp2.x+=dx[i];temp2.y+=dy[i];
			newz=temp2.x*3+temp2.y;
			if(temp2.x>=0&&temp2.x<3&&temp2.y>=0&&temp2.y<3&&newz>=0&&newz<9){
			     swap(temp2.s[z],temp2.s[newz]);
			     if(!vis.count(temp2.s)){
			     	vis.insert(temp2.s);
			     	temp2.steps+=1;
			     	Q.push(temp2);
			     }
			}
		}
	}
   printf("-1\n");

}
int main()
{

	cin>>s1>>s2;
	BFS();
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值