BFS练习

问题 A: Jugs

#include 
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
#include
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;
}

你可能感兴趣的:(Codeup)