8 Puzzle Aizu - ALDS1_13_B (八数码,map去重,bfs())

The goal of the 8 puzzle problem is to complete pieces on 3×33×3 cells where one of the cells is empty space.

In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below.

1 3 0
4 2 5
7 8 6

You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).

1 2 3
4 5 6
7 8 0

Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.

Input

The 3×33×3 integers denoting the pieces or space are given.

Output

Print the fewest steps in a line.

Constraints

  • There is a solution.

Sample Input

1 3 0
4 2 5
7 8 6

Sample Output

4

题意:给你9个数,让你变成 123456780 最终状态,交换位置,只能是0和上下左右四个方向交换,看看到达最终状态最少需要几步;

思路:bfs,map去重,但是代码中用到了两个函数挺好的,比较两个int型数组是不是相等memcmp(a,b,sizeof(a))==0,复制int型数组b复制到int型数组a中 memcpy(a,b,sizeof(a));

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#include<map>
#include<queue>
#define Max 9
int gg[Max]={1,2,3,4,5,6,7,8,0}, s[Max];

int ff[4][2] = {0,-1,1,0,0,1,-1,0};
int sum;
struct node
{
	int a[Max];
	int step;
};
map<int ,int >m;


int bfs()
{
	node tt;
	memcpy(tt.a,s,sizeof(s));    // int 型数组进行复制; 
	tt.step = 0;
	queue<node > q;
	q.push(tt);
	while(!q.empty())
	{
		node star = q.front();
		q.pop();
		int i;
		for(i = 0;i<9;i++)
			if(star.a[i]==0)
				break;
		int y = i/3;
		int x = i%3;
		for(i = 0;i<4;i++)
		{
			int tx = x + ff[i][0];
			int ty = y + ff[i][1];
			if(tx >= 0&&ty>=0&&ty<3&&tx<3)
			{
				node end;
				memcpy(end.a,star.a,sizeof(star.a));
				int k = ty*3+tx;
				swap(end.a[k],end.a[y*3+x]);
				int sum1 = 0;
				for(int j = 0;j<9;j++)
					sum1 = sum1*10+end.a[j];
				if(!m[sum1])      // map 去重; 
				{
					m[sum1] = sum++;
					end.step = star.step+1;
					if(memcmp(end.a,gg,sizeof(gg))==0)
						return end.step;
					q.push(end);
				}
			}
		}
	}
}
int main()
{
	int i,j;

	while(~scanf("%d",&s[0]))
	{
		m.clear();
		int k = s[0];
		sum = 1;
		for(i = 1;i<9;i++)
		{
			scanf("%d",&s[i]);
			k = k*10+s[i];
		}
		m[k] = sum++;
		if(memcmp(s,gg,sizeof(gg))==0)   // 比较int型的数组是不是相等; 
			printf("0\n");
		else printf("%d\n",bfs());
		
	}	
	return 0;
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值