没考虑必须跨过不同色棋子也能过?
查看原帖
没考虑必须跨过不同色棋子也能过?
633339
ZJH123767楼主2023/11/3 19:41
#include<bits/stdc++.h>
using namespace std;
int n;
string bg;
map<string,int> d;
map<string,string> last;
map<string,int> id;
string ed;
queue<string> q;
void bfs() {
	q.push(bg);
	d[bg]=0;
	last[bg]="";
	id[bg]=-1;
	if(bg==ed)return;
	while(!q.empty()) {
		string p=q.front();
		q.pop();
		for(int i=0; i<p.size(); i++) {
			if(p[i]==' ') {
				if(i-1>=0) {
					if(p[i-1]=='W') {
						string t=p;
						t[i-1]=' ';
						t[i]='W';
						if(d.find(t)==d.end()){
							id[t]=i-1;
							last[t]=p;
							d[t]=d[p]+1;
							q.push(t);
						}
						if(t==ed)return;
					}
				}
				if(i+1<p.size()) {
					if(p[i+1]=='B') {
						string t=p;
						t[i+1]=' ';
						t[i]='B';
						if(d.find(t)==d.end()){
							id[t]=i+1;
							last[t]=p;
							d[t]=d[p]+1;
							q.push(t);
						}
						if(t==ed)return;
					}
				}
				if(i-2>=0){
					if(p[i-2]=='W'){
						string t=p;
						t[i-2]=' ';
						t[i]='W';
						if(d.find(t)==d.end()){
							id[t]=i-2;
							last[t]=p;
							d[t]=d[p]+1;
							q.push(t);
						}
						if(t==ed)return;
					}
				}
				if(i+2<p.size()){
					if(p[i+2]=='B'){
						string t=p;
						t[i+2]=' ';
						t[i]='B';
						if(d.find(t)==d.end()){
							id[t]=i+2;
							last[t]=p;
							d[t]=d[p]+1;
							q.push(t);
						}
						if(t==ed)return;
					}
				}
				break;
			}
		}
	}
}
int main() {
	cin>>n;
	for(int i=1; i<=n; i++)bg=bg+"W",ed=ed+"B";
	bg=bg+" ",ed=ed+" ";
	for(int i=1; i<=n; i++)bg=bg+"B",ed=ed+"W";
	bfs();
//	cout<<d[ed]<<endl;
	vector<int> ans;
	for(string s=ed;s!="";s=last[s]){
		ans.push_back(id[s]+1);
	}
	reverse(ans.begin(),ans.end());
	for(int i=1;i<ans.size();i++){
		cout<<ans[i]<<' ';
		if(i%20==0)cout<<endl;
	}
	return 0;
}

我的代码,没考虑必须只能跳过不同色棋子,结果也能过?求合理性

2023/11/3 19:41
加载中...