《挑战程序设计竞赛(疑惑)》19.2九宫格拼图

不知道为什么用二维数组来实现不能,留给未来的我来解决吧。

#define N 3
#define M 4

#include 
#include
#include
#include
using namespace std;
struct Puzzle 
{
	int grids[N][N];//拼图坐标的二维数组描述
	string path = "";//路径
	int space_x;
	int space_y;//目标点的坐标
	bool operator < (const Puzzle &p) const
	{
		for (int i = 0; i < N; i++)
		{
			for (int j = 0; j < N; j++)
			{
				if (grids[i][j] == p.grids[i][j]) continue;
				return grids[i][j]< p.grids[i][j];
			}
		}
		return false;
	}
};
//确立方向的变化
static const char dir[M] = {'L','R','U','D'};
static const int dx[M] = {0, 0, -1, 1};
static const int dy[M] = {-1, 1, 0, 0};
bool is_target(Puzzle tp)//判断是否到达目标状态
{
	for (int i = 0; i < N; i++)
	{
		for (int j = 0; j < N; j++)
		{
			if (tp.grids[i][j] != (3 * i + j + 1))
			{
				return false;
			}
		}
	}
	return true;
}

string bfs(Puzzle tp)//用宽度搜索进行状态转移
{
	Puzzle tp2;
	queue<Puzzle> qu;
	map<Puzzle, bool>Cut;
	tp.path = "";
	qu.push(tp);
	Cut[tp] = true;
	while(!qu.empty())
	{
		printf("1\n");
		tp2 = qu.front(); qu.pop();
		if (is_target(tp2)) 
		{
			return tp2.path;
		}
		for (int i = 0; i < M; i++)
		{
			int space_x = tp2.space_x+dx[i];
			int space_y = tp2.space_y+dy[i];
			if (space_x < 0 || space_y < 0 || space_x >= N || space_y >= N)
			{
				continue;
			}
			swap(tp2.grids[tp2.space_x][tp2.space_y], tp2.grids[space_x][space_y]);
			tp2.space_x = space_x;
			tp2.space_y = space_y;
			if (!Cut[tp2])
			{
				Cut[tp2] = true;
				tp2.path += dir[i];
				qu.push(tp2);
			}
		}
	}
	return "unsolvable";
}

int main()
{
	Puzzle sp;
	//初始化拼图坐标
	for (int i = 0; i < N; i++)
	{
		for (int j = 0; j < N; j++)
		{
			cin>>sp.grids[i][j];
			if (sp.grids[i][j] == 0)
			{
				sp.grids[i][j] = N*3;
				sp.space_x = i;
				sp.space_y = j;
			}
		}
	}
	for (int i = 0; i < N; i++)
	{
		for (int j = 0; j < N; j++)
		{
			cout << sp.grids[i][j]<<" ";
		}
		cout<<"\n";
	}
	cout << is_target(sp)<<"\n";
	string ans = bfs(sp);
	cout << ans;
	system("pause");
	return 0;
}

你可能感兴趣的:(数据结构)