uva 10085(隐式图搜索)

题意:给出了3*3的棋盘,有一个是空白的表示为0,其他地方都填了1到8互不相同的棋子,可以让与空白位置相邻的上下左右的棋子移动到空白位置,要求输出棋子能移动到和初始位置状态最不同的样子和移动步骤。

题解:bfs,用一个结构体存每种棋盘状态,移动步数和移动步骤,每次移动后并且不重复,在加入队列之前,对比当前步数和之前的,步数大的更新结果中的棋盘状态和步骤。

#include <stdio.h>
#include <string.h>
#include <cmath>
#include <algorithm>
#include <map>
#include <queue>
#include <string>
#include <iostream>
using namespace std;
const int N = 3;
struct ST {
	int ch[N][N];
	int x, y, step;
	string str;
}st, st1;
queue<ST> q;
map<long long, int> m;
int init[N][N], ans, res[N][N];
string str1;
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
const char dir[] = {'U', 'D', 'L', 'R'};

int hash(ST temp) {
	long long cnt, k;
	cnt = k = 0;
	for (int i = 0; i < N; i++)
		for (int j = 0; j < N; j++)
			cnt += temp.ch[i][j] * pow(9, k++);
	if (!m[cnt]) {
		m[cnt] = 1;
		return 1;
	}
	return 0;
}

void bfs() {
	q.push(st);
	while (!q.empty()) {
		st = q.front();
		q.pop();
		for (int i = 0; i < 4; i++) {
			int x1 = st.x + dx[i];
			int y1 = st.y + dy[i];
			if (x1 < 0 || x1 >= N || y1 < 0 || y1 >= N)
				continue;
			st1 = st;
			st1.ch[st1.x][st1.y] = st1.ch[x1][y1];
			st1.ch[x1][y1] = 0;
			st1.x = x1;
			st1.y = y1;
			st1.str += dir[i];	
			if (hash(st1)) {
				st1.step += 1;
				if (st1.step > ans) {
					ans = st1.step;
					memcpy(res, st1.ch, sizeof(res));		
					str1 = st1.str;
				}
				q.push(st1);
			}
		}
	}
}

int main() {
	int t, k = 1;
	scanf("%d", &t);
	while (t--) {
		ans = 0;
		m.clear();
		for (int i = 0; i < 3; i++)
			for (int j = 0; j < 3; j++) {
				scanf("%d", &st.ch[i][j]);
				if (st.ch[i][j] == 0) {
					st.x = i;
					st.y = j;
				}
			}
		st.step = 0;
		st.str = "";
		hash(st);
		bfs();
		printf("Puzzle #%d\n", k++);
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < N - 1; j++)
				printf("%d ", res[i][j]);
			printf("%d\n", res[i][N - 1]);
		}
		cout << str1 << endl;
		printf("\n");
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值