八数码问题的超简单STL版

问题描述:
在3×3的棋盘上,摆有八个棋子,每个棋子上标有1至8的某一数字。棋盘中留有一个空格,空格用0来表示。空格周围的棋子可以移到空格中。要求解的问题是:给出一种初始布局(初始状态)和目标布局123804765,找到一种最少步骤的移动方法,实现从初始布局到目标布局的转变。
输入
一行,9个数,表示方阵的初始状态
输出
一行,一个整数,表示最少步数。若在5000步内无解,则输出-1.
样例输入
123840765
样例输出
1
提示
解释:样例中123840765是3*3的方阵
1 2 3
8 4 0
7 6 5
目标方阵是:
1 2 3
8 0 4
7 6 5
从学习宽搜的那年开始,每年都要写一次,这次写了个超简单版的,主要是C++里的STL帮了大忙。详细看下面代码,我想,懂BFS框架的小白应该也能轻松驾驭它了吧。

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 362800+16;
string endS = "123804765"; 
struct node{
	string s;
	int pos,step;//s表示状态,pos表示0所在的位置,step步数。 
};
queue<node>q;
map<string ,bool> mp;
int changeId[9][4] = {
					{-1,-1,3,1},{-1,0,4,2},{-1,1,5,-1},
					{0,-1,6,4},{1,3,7,5},{2,4,8,-1},
					{3,-1,-1,7},{4,6,-1,8},{5,7,-1,-1}
					};//0出现在0->8的位置后该和哪些位置交换 

void swapS(string &s,int pos ,int topos){
	char t ;
	t = s[pos],s[pos] = s[topos] , s[topos] = t;
}
int bfs(string s,int pos0){
	q.push((node){s,pos0,0});
	mp[s] = true;
	while(!q.empty()){	
		node head = q.front();
		q.pop();
		int pos = head.pos;
		string cur = head.s;
		if(cur == endS)		return head.step;
		if(head.step> 5000) return -1;
		for(int i = 0; i< 4; i++){ //四个方向上交换 
			string newCur = cur;
			int topos = changeId[pos][i];  //因为将0在每个位置上可以交换的位置进行了打表,减少了程序代码量。 
			if(topos != -1){
				swapS(newCur,pos,topos);
				if(!mp[newCur]){ //新产生的状态如果没有出现过,则入队列标状态。 
					q.push((node){newCur,topos,head.step+1});
					mp[newCur] = true;
				}
			}
		}
		
	}
	return -1;
}
int main(){
	int pos0,ans = 0;
	string starts;
	cin >> starts;
	//找0所在的位置 
	pos0 = starts.find('0');
	if(starts != endS) ans = bfs(starts,pos0);
	cout << ans;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值