BFS经典问题八数码问题

1、问题描述

人称不做这道题目会后悔,杭电OJ链接:http://acm.hdu.edu.cn/showproblem.php?pid=1043.
八数码问题,跟我们小时候玩得滑块拼图如出一辙。每个格子只能往空格处移动。如下左图所示:
在这里插入图片描述 在这里插入图描述
这里八数码问题如下图所示:X是空格,我们对左侧的状态进行如下的3步操作即可转移到目标状态。
在这里插入图片描述

2、求解方法(直接BFS)

一看BFS可以求解,于是很快写完一个BFS,思路是从每次给定的状态BFS到最终状态[12345678x],结果是超时的。因为对于每个case都会进行大量的搜索,特别对于无解的情况,会搜遍所有的情况,因此必然超时。
超时代码如下:

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

string str;
map<string, int> visit;
struct Node{ 
	string status,path; 
	Node(string s = "", string p = "") {
		status = s;
		path = p;
	}
};
void swap(string& s, int i, int j){
	char c = s[i]; s[i] = s[j]; s[j] = c; 
}
string Up(string str)   {
	int pos = str.find("x");
	if (pos <= 2) return "";
	swap(str, pos, pos - 3);
	return str;
}
string Down(string str)   {
	int pos = str.find("x");
	if (pos >= 6) return "";
	swap(str, pos, pos + 3);
	return str;
}
string Left(string str)   {
	int pos = str.find("x");
	if (pos == 0 || pos == 3 || pos == 6) return "";
	swap(str, pos, pos - 1);
	return str;
}
string Right(string str)   {
	int pos = str.find("x");
	if (pos == 2 || pos == 5 || pos == 8) return "";
	swap(str, pos, pos + 1);
	return str;
}

string bfs(){
	visit[str] = 1;
	queue<Node> Q;
	Q.push(Node(str));
	while (!Q.empty()){
		Node cn = Q.front();
		Q.pop();
		if (cn.status == "12345678x")
			return cn.path;
		string news = Up(cn.status);
		if (news != "" && visit[news] != 1){
			visit[news] = 1;
			Q.push(Node(news, cn.path + "u"));
		}
		news = Down(cn.status);
		if (news != "" && visit[news] != 1){
			visit[news] = 1;
			Q.push(Node(news, cn.path + "d"));
		}
		news = Left(cn.status);
		if (news != "" && visit[news] != 1){
			visit[news] = 1;
			Q.push(Node(news, cn.path + "l"));
		}
		news = Right(cn.status);
		if (news != "" && visit[news] != 1){
			visit[news] = 1;
			Q.push(Node(news, cn.path + "r"));
		}
	}
	return "unsolvable";
}

int main(){
	string tstr;
	while (getline(cin, tstr)){
		visit.clear();
		str = "";
		for (int i = 0; i < tstr.length(); i++)
		if (tstr[i] != ' ')
			str += tstr[i];
		cout << bfs() << endl;
	}
	return 0;
}
3、求解方法(反向BFS)

我们发现,对于所有的状态他们的最终状态都是[12345678x],因此可以改变思路,我们可以从终态反向搜索其余所有状态。看过别人的代码,BFS需要记录每一个已经遍历过的状态,这里的每一个状态就是一个字符串,比如[12345x678]或[123x54678],网上的很多做法是将x替换为9,然后将每个字符串映射为一个整数(康托展开,实际是求这个字符串在字典序下的序号),我发现直接使用map也可以。正确代码如下所示:

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

map<string, string> path;
int dir[4][2] = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
string dirs = "udlr";

void swap(string& s, int i, int j){
	char c = s[i]; s[i] = s[j]; s[j] = c;
}

void bfs(){
	string start_stat = "123456789";
	path[start_stat] = "s";
	queue<string> Q;
	Q.push(start_stat);
	while (!Q.empty()){
		string curr_stat = Q.front();
		Q.pop();
		int pos = curr_stat.find("9");
		int x = pos / 3, y = pos % 3;
		for (int i = 0; i < 4; i++){
			int nx = x + dir[i][0], ny = y + dir[i][1];
			if (nx < 0 || nx >= 3 || ny < 0 || ny >= 3) continue;
			int next_pos = nx * 3 + ny;
			string next_stat = curr_stat;
			swap(next_stat, pos, next_pos);
			if (path[next_stat] == ""){
				path[next_stat] = path[curr_stat] + dirs[i];
				Q.push(next_stat);
			}
		}
	}
}

int main()
{
	bfs();
	string str, tstr;
	while (getline(cin, tstr)){
		str = "";
		for (int i = 0; i < tstr.length(); i++){
			if (tstr[i] != ' ')
				str += tstr[i];
		}
		replace(str.begin(), str.end(), 'x', '9');
		if (path[str] != ""){
			string sp = path[str];
			reverse(sp.begin(), sp.end());
			for (int i = 0; i < sp.length(); i++){
				if (sp[i] == 'l') cout << "r";
				else if (sp[i] == 'r') cout << "l";
				else if (sp[i] == 'u') cout << "d";
				else if (sp[i] == 'd') cout << "u";
			}
			cout << endl;
		}
		else
			cout << "unsolvable" << endl;
	}
	return 0;   
}

针对该问题,网上有多达7种解法,其余的解法后续继续研究。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Researcher-Du

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值