计蒜客 ·八数码问题

【BFS】

初见安~本题选自计蒜客。

Description

八方块移动游戏要求从一个含 8 个数字(用 1-8 表示)的方块以及一个空格方块(用 0 表示)的 3 × 3 矩阵的起始状态开始,不断移动该空格方块以使其和相邻的方块互换,直至达到所定义的目标状态。空格方块在中间位置时有上、下、左、右 4 个方向可移动,在四个角落上有 2个方向可移动,在其他位置上有 3 个方向可移动。例如,假设一个 3× 3 矩阵的初始状态为:

8 0 3
2 1 4
7 6 5

目标状态为:

1 2 3
8 0 4
7 6 5

则一个合法的移动路径为:

8 0 3 > 8 1 3 > 8 1 3 > 0 1 3 > 1 0 3 > 1 2 3
2 1 4 > 2 0 4 > 0 2 4 > 8 2 4 > 8 2 4 > 8 0 4
7 6 5 > 7 6 5 > 7 6 5 > 7 6 5 > 7 6 5 > 7 6 5

另外,在所有可能的从初始状态到目标状态的移动路径中,步数最少的路径被称为最短路径;在上面的例子中,最短路径为 5 。如果不存在从初试状态到目标状态的任何路径,则称该组状态无解。 请设计有效的(细节请见评分规则)算法找到从八方块的某初试状态到某目标状态的所有可能路径中的最短路径。

Input

程序需读入初始状态和目标状态,这两个状态都由 9 个数字组成( 0 表示空格, 1-8 表示 8个数字方块),每行 3 个数字,数字之间用空格隔开。

Output

如果输入数据有解,输出一个表示最短路径的非负的整数;如果输入数据无解,输出 -1 。

Sample Input

8 0 3
2 1 4
7 6 5
1 2 3
8 0 4
7 6 5

Sample Output

5

题解

本题就不得不用BFS来做了——过程为交换‘0’和上下左右任意方向的数字,直到拼出目标状态。就挺有BFS“不撞南墙不回头”的理念。大致思路是很简单的。

在存储和设置变量上,为了对比目标状态,我们可以为走的每一步后的状态——二维数组,开一个结构体并重定向“==”。但依据BFS的搜索套路,需要一个vis来记录是否走过这一步——即这个状态是否凑出来过。我们可以选择在结构体里顺便标一个号,or用一个set集合去重——但set会有一个内部的自动排序,所以我们还要重定向一个“<”or">"(因为我们实际上用不到)

代码如下——

#include<bits/stdc++.h>
using namespace std;
int sa,sb;
int dir[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
bool in(int a,int b)//检查是否越界
{
	if(a>=0&&a<=2&&b>=0&&b<=2) return true;
	return false;
}
struct node
{
	int a[3][3];//状态
	int d,x,y;//步数及‘0’的位置
	bool operator < (const node &x) const
	{
		for(int i=0;i<3;i++)
			for(int j=0;j<3;j++)
			{
				if(a[i][j]!=x.a[i][j]) return a[i][j]<x.a[i][j];
			}
		return false;
	}
	bool operator == (const node &x) const
	{
		for(int i=0;i<3;i++)
			for(int j=0;j<3;j++)
			{
				if(a[i][j]!=x.a[i][j]) return false;
			}
		return true;
	}
}from,to; 
int bfs()
{
	queue<node> q;
	q.push(from);
	set<node> st;
	st.insert(from);//存入原状态
	while(!q.empty())
	{
		node now=q.front();
		q.pop();
		for(int i=0;i<4;i++)
		{
			int ta=now.x+dir[i][0];
			int tb=now.y+dir[i][1];
			if(in(ta,tb))
			{
				node tmp=now;
				tmp.d++;
				swap(tmp.a[ta][tb],tmp.a[now.x][now.y]);
				if(!st.count(tmp))
				{
					if(tmp==to) return tmp.d;//达到目标状态,直接返回
					tmp.x=ta;tmp.y=tb;//没有则存入继续
					q.push(tmp); 
					st.insert(tmp);
				}
			}
		}
	}
	return -1;
}
int main()
{
	for(int i=0;i<3;i++)
		for(int j=0;j<3;j++)
		{
			cin>>from.a[i][j];
			if(from.a[i][j]==0)//找到了初始的‘0’
			{
				from.x=i;from.y=j;
			}
		}
	for(int i=0;i<3;i++)
		for(int j=0;j<3;j++)
			cin>>to.a[i][j];
	cout<<bfs()<<endl;
	return 0;
}

迎评:)
——End——

猜你喜欢

转载自blog.csdn.net/qq_43326267/article/details/82937517