蓝桥杯 PREV-19 九宫重排(bfs)

本文介绍了一种使用广度优先搜索(BFS)算法来解决拼图游戏问题的方法。通过详细解释算法思路,展示了如何利用map容器记录状态并进行搜索,最终找到从初始状态到目标状态的最少移动步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:

http://lx.lanqiao.cn/problem.page?gpid=T42

思路:

既然是求最少次数,那就用bfs搜索;
每次寻找下一种可能的状态,用map容器记录即可;

代码:

#include<bits/stdc++.h>

using namespace std;

bool tag[10][10];
string s, t, now;
map<string, int> cnt;
queue<string> que;

inline void bfs(int & p, int & q) {
	int pre = cnt[now];
	swap(now[p], now[q]);
	if(now == t) {
		cout << pre << '\n';
		exit(0);	
	}
	if(!cnt[now]) {	
		que.push(now);
		cnt[now] = pre + 1;
	}
	swap(now[p], now[q]);
}

#define ok(x, y) tag[i * 3 + j][(x) * 3 + y] = tag[(x) * 3 + y][i * 3 + j] = true;
int main() {
#ifdef MyTest
	freopen("Sakura.txt", "r", stdin);
#endif
	for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) {
		if(i > 0) ok(i - 1, j);
		if(i < 2) ok(i + 1, j);
		if(j > 0) ok(i, j - 1);
		if(j < 2) ok(i, j + 1);
	}
	cin >> s >> t;
	cnt[s] = 1;
	que.push(s);
	while(!que.empty()) {
		now = que.front();
		que.pop();
		int p = now.find('.');
		for(int i = 0; i < 9; ++i) if(tag[p][i]) bfs(p, i);
	}
	cout << -1;
	return 0;	
}
九宫重排问题可以使用深度优先搜索算法来解决。下面是使用C++实现的深度优先算法: ```c++ #include <iostream> #include <vector> using namespace std; const int N = 3; const int M = N * N; const int dx[] = {0, 1, 0, -1}; const int dy[] = {1, 0, -1, 0}; vector<int> path; bool dfs(int x, int y, int depth, int prev, int target, int grid[N][N]) { if (depth == target) return true; for (int d = 0; d < 4; ++d) { int nx = x + dx[d], ny = y + dy[d]; if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue; if (nx * N + ny == prev) continue; swap(grid[x][y], grid[nx][ny]); path.push_back(nx * N + ny); if (dfs(nx, ny, depth + 1, x * N + y, target, grid)) return true; path.pop_back(); swap(grid[x][y], grid[nx][ny]); } return false; } int main() { int grid[N][N]; int x, y; for (int i = 0; i < M; ++i) { cin >> grid[i/N][i%N]; if (grid[i/N][i%N] == 0) x = i / N, y = i % N; } int target = 0; for (int i = 0; i < M; ++i) { if (grid[i/N][i%N] != 0) { for (int j = 0; j < i; ++j) { if (grid[j/N][j%N] > grid[i/N][i%N]) target++; } } } if ((x + y + target) % 2 != 0) { cout << "No solution" << endl; return 0; } path.push_back(x * N + y); dfs(x, y, 0, x * N + y, target, grid); for (int i = 0; i < path.size(); ++i) { cout << path[i] << " "; } cout << endl; return 0; } ``` 在这个实现中,我们使用一个二维数组来表示九宫格的状态,其中0表示空格。我们用x和y表示空格的位置。我们还用一个一维数组path来保存深度优先搜索的路径。 在dfs函数中,我们首先判断深度是否达到了目标,如果达到了目标,说明我们已经找到了解,返回true。否则,我们遍历当前位置周围的四个方向,如果可以移动,我们就尝试移动,并将移动后的位置加入到path中。然后递归地调用dfs函数,如果返回true,说明已经找到了解,直接返回true。如果返回false,说明当前方向不能到达目标状态,我们撤回之前的操作,继续尝试其他方向。 在主函数中,我们首先读入九宫格的状态,并计算出初始状态到目标状态的逆序对数。如果逆序对数加上空格的横纵坐标之和是奇数,那么无解,否则调用dfs函数进行搜索。搜索完成后,我们输出path数组中记录的路径即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值