BFS练习

问题 A: Jugs

#include <iostream>
using namespace std;
int main()
{
	int Ca, Cb, n;
	while (cin >> Ca >> Cb >> n)
	{
		int t = 0;
		while (t != n)
		{
			//3 5 4
			//5 7 3
			cout << "fill A" << endl;
			cout << "pour A B" << endl;
			t += Ca;
			if (t > Cb)
			{
				t -= Cb;
				cout << "empty B" << endl;
				cout << "pour A B" << endl;
			}
		}
		cout << "success" << endl;
	}
	return 0;
}

问题 B: DFS or BFS?

#include<iostream>
#include<queue>
using namespace std;

int flag;
char m[10][10];
int dir[9][2] = { {0 , 0}, {1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {-1, -1}, {1, -1}, {-1, 1} };//九个操作
struct node
{
	int x, y;
	int step;
	node(){}
	node(int _x, int _y, int _step)
	{
		x = _x;
		y = _y;
		step= _step;
	}
};

bool in(int x, int y)
{
	return 0 <= x && x < 8 && 0 <= y && y < 8; 
}

void bfs()
{
	queue<node> q;
	q.push(node(7, 0, 0));
	while (!q.empty())
	{
		node now = q.front();
		q.pop();
		if (now.step == 8)//如果石头都掉完了,那么肯定能到A点
		{
			flag = 1;
			return;
		}
		for (int i = 0; i < 9; i++)
		{
			node temp;
			temp.x = now.x + dir[i][0];
			temp.y = now.y + dir[i][1];
			temp.step = now.step + 1;
			if (in(temp.x, temp.y) && m[temp.x - temp.step][temp.y] != 'S' && m[temp.x - temp.step + 1][temp.y] != 'S')
			{
				q.push(temp);
			}
		}
	}

}

int main()
{
	int t, count = 1;
	cin >> t;
	getchar();
	while (t--)
	{
		flag = 0;
		for (int i = 0; i < 8; i++)
		{
			scanf("%s", m[i]);
		}
		bfs();
		if (flag)
		{
			cout << "Case #" << count++ << ": Yes" << endl;
		}
		else
		{
			cout << "Case #" << count++ << ": No" << endl;
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值