UVA 10651 Pebble Solitaire

本文介绍了一种使用深度优先搜索(DFS)解决棋盘上相邻空位问题的算法。通过扫描棋盘并考虑边界条件,算法实现了一个二叉搜索树来决定下一步操作,并利用广搜和剪枝优化来找到最小剩余棋子数量的解决方案。

大意不再赘述。

思路:我想用dfs爆过去,扫描一遍,如果两个相邻并且有空位置的话,对于A、B、C来说,假设A为空,B、C满,注意边界条件,那么当前操作只有两种选择,要么选B,要么选C,搜索树是一棵二叉树,然后加上回溯,剪枝等限制条件在极限条件下过不了,但是广搜可以过,不需要判重,只是找到最小的剩余棋子的个数即可。判 DP的方法还再思考。

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;

struct node
{
	int st[21];
	int step;
}cur, next;

int s[21];

int tot;

int bfs()
{
	queue<node> Q;
	int ans = tot;
	Q.push(cur);
	while(!Q.empty())
	{
		cur = Q.front(); Q.pop();
		for(int i = 0; i < 12; i++) if(cur.st[i])
		{
			next = cur;
			if(i >= 2 && next.st[i-1] && !next.st[i-2])
			{
				next.st[i] = 0, next.st[i-2] = 1, next.st[i-1] = 0;
				next.step--;
				if(ans > next.step) ans = next.step;
				if(ans == 1) break;
				Q.push(next);
			}
			else if(i <= 9 && next.st[i+1] && !next.st[i+2])
			{
				next.st[i] = 0, next.st[i+1] = 0, next.st[i+2] = 1;
				next.step--;
				if(ans > next.step) ans = next.step;
				if(ans == 1) break;
				Q.push(next);
			}
		}
	}
	return ans;
}

void read_case()
{
	char str[26];
	scanf("%s", str);
	tot = 0;
	for(int i = 0; str[i]; i++)
	{
		if(str[i] == '-') s[i] = 0;
		else
		{
			s[i] = 1;
			tot++;
		}
	}
	memcpy(cur.st, s, sizeof(s));
	cur.step = tot;
}

void solve()
{
	read_case();
	int ans = bfs();
	printf("%d\n", ans);
}

int main()
{
	int T;
	scanf("%d", &T);
	while(T--)
	{
		solve();
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值