计蒜客 一维跳棋 BFS

在这里插入图片描述

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#include<queue>
#include<unordered_map>
using namespace std;

unordered_map<string, bool> vis;


struct Node
{
	string status;
	vector<int> step;
	int n_step;

	Node() {};
	Node(string ss, int stepp)
	{
		status = ss;
		n_step = stepp;
	}
}beginn,endd;

queue<Node> qq;
int N;

string exchange(string ss, int x, int y)
{
	char m = ss[x];
	ss[x] = ss[y];
	ss[y] = m;
	return ss;
}


void bfs()
{
	vis[beginn.status] = 1;
	qq.push(beginn);
	while (!qq.empty())
	{
		Node now = qq.front();
		qq.pop();

		if (now.status == endd.status)   //judge the end
		{
			for (int i = 1; i < now.step.size(); i++)
			{
				cout << now.step[i]<<" ";
			}
			break;
		}
		for (int j = -2; j <= 2; j++)     //count next
		{
			if (j == 0 || now.n_step-1 + j<0|| now.n_step-1 + j>2*N)
				continue;
			string next=exchange(now.status, now.n_step-1, now.n_step-1 + j);
			 
			if (!vis[next])      
			{
				int nowstep = now.n_step + j;
				Node add=Node(next, nowstep);
				add.step = now.step;
				add.step.push_back(nowstep);

				qq.push(add);           //push stack
				vis[add.status] = 1;    //update vis

				
			}

		}
	}
}

int main()
{
	cin >> N; 
	for (int i = 0; i < N; i++)
	{
		beginn.status += '1';
		endd.status += '2';

	}
	beginn.status += '0';
	endd.status += '0';
	for (int i = 0; i < N; i++)
	{
		beginn.status += '2';
		endd.status += '1';
	}
	beginn.step.push_back(N + 1);
	endd.step.push_back(N + 1);

	beginn.n_step = N + 1;
	endd.n_step = N + 1;

	bfs();
	return 0;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值