藍橋杯 PREV-19 九宮重排(bfs)

題目鏈接:

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;	
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章