算法实验三 Problem I八数码

Problem I

八数码

时限:5000ms 内存限制:20000K  总时限:10000ms

描述

在九宫格里放在1到8共8个数字还有一个是空格,与空格相邻的数字可以移动到空格的位置,问给定的状态最少需要几步能到达目标状态(用0表示空格):
1 2 3
4 5 6
7 8 0

输入

输入一个给定的状态。

输出

输出到达目标状态的最小步数。不能到达时输出-1。

输入样例

1 2 3
4 0 6
7 5 8

输出样例

2

#include <iostream>
#include <queue>
#include <map>
using namespace std;

struct rec {
	int a[3][3];
	int empty_x, empty_y;
	bool useful;
	int vis;
	int step;
};
queue<rec> q;
rec start, end;
map<int, int> visited;
int maze[3][3];

int dx[4] = {0, 0, -1, 1};

int dy[4] = {-1, 1, 0, 0};

void init() { //初始化
	int temp = 0;;
	for (int i = 0; i < 3; i++) {
		for (int j = 0; j < 3; j++) {
			cin >> maze[i][j];
			start.a[i][j] = maze[i][j];
			if (maze[i][j] == 0) {
				start.empty_x = i, start.empty_y = j;
			}
			temp = temp * 10 + maze[i][j];
		}
	}
	start.vis = temp;
	start.step = 0;
}

bool isTarget(rec next) {
	if (next.a[0][0] == 1 && next.a[0][1] == 2 && next.a[0][2] == 3 && next.a[1][0] == 4 && next.a[1][1] == 5
	        && next.a[1][2] == 6 && next.a[2][0] == 7 && next.a[2][1] == 8 && next.a[2][2] == 0) {
		return true;
	}
	return false;
}

rec moveto(rec now, int i) {
	rec next;
	next.empty_x = now.empty_x + dx[i];
	next.empty_y = now.empty_y + dy[i];
	if (next.empty_x < 0 || next.empty_x >= 3 || next.empty_y < 0 || next.empty_y >= 3) {
		next.useful = false;
		return next;
	}
	for (int i = 0; i < 3; i++) {
		for (int j = 0; j < 3; j++) {
			next.a[i][j] = now.a[i][j];
		}
	}
	next.a[next.empty_x][next.empty_y] = 0;
	next.a[now.empty_x][now.empty_y] = now.a[next.empty_x][next.empty_y];
	int temp = 0;
	for (int i = 0; i < 3; i++) {
		for (int j = 0; j < 3; j++) {
			temp = 10 * temp + next.a[i][j];
		}
	}
	next.vis = temp;
	next.useful = true;
	return next;
}

int bfs() {
	q.push(start);
	while (q.size()) {
		rec now = q.front();
		if (isTarget(now)) {
			return now.step;
		}
		q.pop();
		for (int i = 0; i < 4; i++) {
			rec next = moveto(now, i);
			if (next.useful == true) {
				if (!visited[next.vis]) { //该种状态未被访问
					visited[next.vis] = 1;
					next.step = now.step + 1;
					q.push(next);
				}
			}
		}
	}
	return -1;
}

int main() {
	init();
	cout << bfs() << endl;
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值