AOJ 0121 Seven Puzzle (bfs)

题意:

给你8个格子 0那个格子可以上下左右的动 - - 一开始以为所有格子都能动 毕竟日文题目 那么就很像8数码问题了


由其他格子到“01234567” - - 如果挨个bfs的话 case多肯定TLE 那么思维反向一下 由“01234567”到其他状态 把每个最小步数存到map中 对于每个case直接查找就好了

AC代码如下:

//
//  AOJ 0121 Seven Puzzle
//
//  Created by TaoSama on 2015-02-20
//  Copyright (c) 2014 TaoSama. All rights reserved.
//
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <set>
#include <vector>
#define CLR(x,y) memset(x, y, sizeof(x))

using namespace std;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
const int N = 1e5 + 10;

string s;
typedef pair<string, int> Sta;
map<string, int> dp;
int d[4] = { -1, 1, 4, -4};

void bfs() {
	queue<Sta> q;
	dp["01234567"] = 0; q.push(Sta("01234567", 0));
	while(!q.empty()) {
		string s = q.front().first;
		int cur = q.front().second;
		q.pop();
		for(int i = 0; i < 4; ++i) {
			string ns = s;
			int nxt = cur + d[i];
			if(nxt < 0 || nxt > 7 || cur == 3 && nxt == 4 || cur == 4 && nxt == 3)
				continue;
			swap(ns[cur], ns[nxt]);
			if(!dp.count(ns)) {
				dp[ns] = dp[s] + 1;
				q.push(Sta(ns, nxt));
			}
		}
	}
}
int main() {
#ifdef LOCAL
	freopen("in.txt", "r", stdin);
//	freopen("out.txt","w",stdout);
#endif
	ios_base::sync_with_stdio(0);

	bfs();
	while(cin >> s) {
		for(int i = 1; i <= 7; ++i) {
			char x; cin >> x;
			s += x;
		}
		cout << dp[s] << endl;
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值