蓝桥杯 九宫重排(bfs)

#include<iostream>
#include<algorithm>
#include<vector>
#include<map>
#include<queue>
using namespace std;
vector<vector<char> > start(3,vector<char>(3,0)),goal = start; 
int dx[4] = {-1,0,1,0};
int dy[4] = {0,1,0,-1};
struct node{
	int x,y,step;
	vector<vector<char> > map;
};
map<vector<vector<char> >,bool> vis;
int bfs(int x1,int y1){
	node cur,next;
	cur.x = x1,cur.y = y1,cur.step = 0,cur.map = start;
	if(cur.map == goal) return cur.step; 
	queue<node> q;
	q.push(cur);
	while(q.size()){
		cur = q.front();
		q.pop();
		next.step = cur.step + 1;
		for(int i = 0;i < 4;i ++){
			next.x = cur.x + dx[i],next.y = cur.y + dy[i];
			if(next.x >= 0 && next.x < 3 && next.y >= 0 && next.y < 3){
				next.map = cur.map;
				swap(next.map[cur.x][cur.y],next.map[next.x][next.y]);
				if(vis[next.map] == 0){
					if(next.map == goal) return next.step;
					vis[next.map] = 1;
					q.push(next);
				}
			}
		}
	}
}
int main()
{
	int x1,y1;
	for(int i = 0;i < 3;i ++){
		for(int j = 0;j < 3;j ++){
			cin>>start[i][j];
			if(start[i][j] == '.') x1 = i, y1 = j;
		}
	}
	for(int i = 0;i < 3;i ++)
		for(int j = 0;j < 3;j ++)
			cin>>goal[i][j];
	cout<<bfs(x1,y1)<<endl;
	return 0; 
} 

猜你喜欢

转载自blog.csdn.net/weixin_41988889/article/details/89501871
今日推荐