跳到正文

个人记录

7.9总结(BFS提高)

24TAOTAO约 6 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 6 分钟

版本

  1. v1当前

P1379 八数码难题

题目传送门


解题思路

这道题是让问我们从初始状态到目标状态所需的步数是多少,这里主要讲 BFSBFS 该怎么写。这道题虽然是个棋盘上的问题,应该是二维数组,但它的输入方式是字符串,我们想想有没有方式不用二维数组也能做。其实是有的,我们直接在字符串上操作,这时候我们发现,二维的往上走,相当于展开后往前走三个,接着我们就可以直接在 BFSBFS 里面模拟,方向数组按刚刚的思路推,但是要注意,边缘上,是不能往左/右走的,这时,就要特判一下,还有,因为是关于 00 的运动,所以我们要先找出 00 的位置,其余,与正常做法差不多


参考代码

C++
#include <iostream>
#include <string>
#include <map>
#include <queue>
using namespace std;
int dx[4] = {-3, 3, -1, 1}, x;
string ss, ts = "123804765";
map<string, int> mp;
void bfs()
{
	queue<string> q;
	q.push(ss);
	mp[ss] = 1;
	while (!q.empty())
	{
		string t = q.front();
		q.pop();
		if (t == ts) {cout << mp[t] - 1; return;}
		for (int i = 0; i < 9; i ++) if (t[i] == '0') {x = i; break;}
		for (int i = 0; i < 4; i ++)
		{
			if ((x == 2 && i == 3) || (x == 3 && i == 2) || (x == 5 && i == 3) || (x == 6 && i == 2) || (x == 8 && i == 3)) continue;
			int nx = x + dx[i];
			if (nx < 0 || nx > 8) continue;
			cout << nx << " " << x << '\n';
			string ns = t;
			swap(ns[x], ns[nx]);
			cout << ns << " " << ss << '\n';
			if (mp[ns]) continue;
			mp[ns] = mp[t] + 1;
			q.push(ns);
		}
	}
	return;
}
int main()
{
	cin >> ss;
	bfs();
	for (auto i : mp) cout << i.first << " " << i.second << '\n';
	return 0;
}

P2730 [USACO3.2] 魔板 Magic Squares

题目传送门


解题思路

其实这道题与上道题让我们完成的目标是一样的,其实这两道题从做法和思路上都会有点相似。题目说有三种基础操作,那么就要写出来,可以用函数,方便调用,基础操作的逻辑就是 swapswap,只不过有些容易写错,这里需要反复推演,看看是否符合题意,题目还让我们记录路径,这里可以一起写在 nodenode 里,每次看看,如果这次能做 AA 操作,那么就顺便在压入队列的时候,将其记录,对于这些操作,我们一个一个试,如果可以,就压入队列,顺便还要记录步数,最后将步数和路径直接输出就行了, 用来记录路径的时候,可以使用 stringstring,相较于数组,更方便快捷,输入的时候,因为输入数据里有空格,所以要用一个 charchar 存这,然后将 charchar 变量压入字符串


参考代码

C++
#include <iostream>
#include <string>
#include <queue>
#include <map>
using namespace std;
struct node
{
	string s, path;
	int step;
};
const int N = 10;
char a;
string ss = "12345678", ts;
map<string, bool> mp;
string changea(string s)
{
	swap(s[0], s[7]), swap(s[1], s[6]);
	swap(s[2], s[5]), swap(s[3], s[4]);
	return s;
}
string changeb(string s)
{
	swap(s[2], s[3]), swap(s[2], s[1]), swap(s[1], s[0]);
	swap(s[4], s[5]), swap(s[6], s[5]), swap(s[6], s[7]);
	return s;
}
string changec(string s)
{
	swap(s[2], s[5]); swap(s[2], s[1]); swap(s[1], s[6]);
	return s;
}
void bfs()
{
	queue<node> q;
	q.push({ss, "", 0});
	mp[ss] = 1;
	while (!q.empty())
	{
		node t = q.front();
		q.pop();
		if (t.s == ts) {cout << t.step << "\n" << t.path; return;}
		string ns = changea(t.s);
		if (mp[ns] == 0)
		{
			mp[ns] = 1;
			q.push({ns, t.path + "A", t.step + 1});
		}
		ns = changeb(t.s);
		if (mp[ns] == 0)
		{
			mp[ns] = 1;
			q.push({ns, t.path + "B", t.step + 1});
		}
		ns = changec(t.s);
		if (mp[ns] == 0)
		{
			mp[ns] = 1;
			q.push({ns, t.path + "C", t.step + 1});
		}
	}
	return;
}
int main()
{
	for (int i = 1; i <= 8; i ++) cin >> a, ts += a;
	bfs();
	return 0;
}
原文