洛谷P1518 [USACO2.4]两只塔姆沃斯牛 The Tamworth Two进阶解法

#include<iostream>

using namespace std;
char a[12][12];
int n = 1, m = 0;
struct Animal
{
	char name;
	int location_x, location_y, direction;
}farmer,cows;

void initialize(Animal& s,char c,int i,int j)
{
	s.name = c;
	 s.location_x = i;
	 s.location_y = j;
}

void start(void)
{
	for (int i = 1; i < 11; i++)
		for (int j = 1; j < 11; j++)
		{
			cin >> a[i][j];
			if (a[i][j] == 'F')
				initialize(farmer, 'F',i,j);
			else if (a[i][j] == 'C')
				initialize(cows, 'C',i,j);
		}
}

void go(Animal& s)
{
	switch (s.direction)
	{
	case 0:
		if (a[s.location_x - 1][s.location_y] == '\0' || a[s.location_x - 1][s.location_y] == '*')
			s.direction = 1;
		else
		{
			a[s.location_x-1][s.location_y] = s.name;
			a[s.location_x][s.location_y] = '.';
			s.location_x--;
		}
		break;
	case 1:
		if (a[s.location_x][s.location_y + 1] == '\0' || a[s.location_x][s.location_y + 1] == '*')
			s.direction = 2;
		else
		{
			a[s.location_x][s.location_y+1] = s.name;
			a[s.location_x][s.location_y] = '.';
			s.location_y++;
		}
		break;
	case 2:
		if (a[s.location_x + 1][s.location_y] == '\0' || a[s.location_x + 1][s.location_y] == '*')
			s.direction = 3;
		else
		{
			a[s.location_x+1][s.location_y ] = s.name;
			a[s.location_x][s.location_y] = '.';
			s.location_x++;
		}
		break;
	case 3:
		if (a[s.location_x][s.location_y - 1] == '\0' || a[s.location_x][s.location_y - 1] == '*')
			s.direction = 0;
		else
		{
			a[s.location_x][s.location_y -1] = s.name;
			a[s.location_x][s.location_y] = '.';
			s.location_y--;
		}
	}
}

bool compare(const Animal& s, const Animal& t)
{
	if (t.location_x == s.location_x && t.location_y == s.location_y)
		return true;
	else
		return false;
}

void search(void)
{
	for (;;n++)
	{
		go(farmer);
		go(cows);
		if (compare(farmer, cows))
			break;
		if (n > 10000)
		{
			n = 0;
			break;
		}
	}
}

void show(void)
{
	cout << n;
}

int main()
{
	start();
	search();
	show();
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值