AcW 845 八数码 【BFS、queue、unordered_map】

#include <iostream>
#include <set>
#include <map>
#include <queue>
#include <vector>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <unordered_map>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long LL;
const int MAXN = 1e5+10;
string startt;
string endd = "12345678x";
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
/*
	将3*3网格用string存储
*/
int bfs() {
	// 用于BFS的一个队列 
	queue<string> q;
	// 每一个string对应的distance的哈希map 
	unordered_map<string, int> d;
	// 用来记录distance的数组 每次搜索并记录 
	d[startt] = 0;	
	q.push(startt);
	
	while(q.size()) {
		// 当前字符序列 
		string t = q.front();
		q.pop();
		int distance = d[t];
		if(t == endd) {
			return distance;
		}
		
		// 将x在string中的位置转换到网格中 x y分别是横纵坐标 
		int k = t.find('x');
		int x = k / 3, y = k % 3;
		// 对网格进行一层BFS 
		for(int i = 0; i < 4; i++) {
			int a = x + dx[i], b = y + dy[i];
			if(a >= 0 && a < 3 && b >= 0 && b < 3) {
				// 用t暂存变换完的字符串 
				swap(t[k], t[a*3 + b]);
				// 如果没有过则入队 
				if(!d.count(t)) {
					q.push(t);
					d[t] = distance + 1;
				}
				// 恢复t 
				swap(t[k], t[a*3 + b]);
			}			
		}
	}
	return -1;
}

int main() {
	for(int i = 0; i < 9; i++) {
		char c;
		cin >> c;
		startt += c;
	}	
	cout << bfs() << endl;
	return 0;
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值