宇月幸成


私信TA

用户名:3350680655

访问量:13569

签 名:

题解都沉没在OJ里了..

等  级
排  名 396
经  验 4884
参赛次数 1
文章发表 47
年  龄 24
在职情况 学生
学  校
专  业 软件工程

  自我简介:

刷题打发时间,没别的事做了

解题思路:
BFS枚举状态的典型题
注意事项:
注意每个位置的字符的换法,看起来是有左右两种换法,实际上左->右和右->左是一个情况,所以可以直接省去
参考代码:

#include <iostream>
#include <map>
#include <queue>
#include <algorithm>
using namespace std;
#define x first
#define y second
typedef pair<string, int > PII;
// 估计用数组难以标记访问否,故而用map了.. 
map<string, bool > visited;
int n;
int bfs(string str) {
	queue<PII > que;
	que.push(PII(str, 0));
	visited[str] = true;
	while (que.size()) {
		PII p = que.front();que.pop();
		// 如果找到了合法状态,返回最短路步数.. 
		if (p.x.find("2012") != p.x.npos) return p.y;
		for (int i = 0; i < n - 1; i++) {
			string temp = p.x;
			swap(temp[i + 1], temp[i]);
			if (visited[temp]) continue;
			visited[temp] = true;
			que.push(PII(temp, p.y + 1)); 
		}
	}
	return -1;
}
int main() {
	cin >> n;
	string str;
	cin >> str;
	cout << bfs(str);
	return 0;
}
 

0.0分

2 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答

代码解释器

  评论区

2022-03-12 15:30:04
  • «
  • 1
  • »