P1518 [USACO2.4]两只塔姆沃斯牛 The Tamworth Two
题目链接
题目思路
模拟农夫和奶牛行动路线,为了避免死循环,当ans到一定值时跳出
题目代码
#include <iostream>
#include <algorithm>
using namespace std;
char g[12][12];
int main()
{
int cfx, cfy, ffx, ffy;
for(int i = 0; i < 10; i ++ )
for(int j = 0; j < 10; j ++ )
{
cin >> g[i][j];
if(g[i][j] == 'F') ffx = i, ffy = j;
if(g[i][j] == 'C') cfx = i, cfy = j;
}
int cf = 0, ff = 0, ans = 0;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
while(ffx != cfx || ffy != cfy)
{
if(ans >= 100000)
{
cout << "0" << endl;
return 0;
}
ffx += dx[ff % 4], ffy += dy[ff % 4];
cfx += dx[cf % 4], cfy += dy[cf % 4];
if(ffx < 0 || ffx >= 10 || ffy < 0 || ffy >= 10 || g[ffx][ffy] == '*')
{
ffx -= dx[ff % 4], ffy -= dy[ff % 4];
ff ++ ;
}
if(cfx < 0 || cfx >= 10 || cfy < 0 || cfy >= 10 || g[cfx][cfy] == '*')
{
cfx -= dx[cf % 4], cfy -= dy[cf % 4];
cf ++ ;
}
ans ++ ;
}
cout << ans << endl;
return 0;
}
孤独本是常态

浙公网安备 33010602011771号