蓝桥杯2014年第五届真题-兰顿蚂蚁 - C语言网 (dotcpp.com)
较简单,使用switch语句(别忘记break)。
看清题目!因为看反条件debug半天。
/*
兰顿蚂蚁2014
平面上的正方形格子被填上黑色或白色。在其中一格正方形内有一只“蚂蚁”。
蚂蚁的头部朝向为:上下左右其中一方。
蚂蚁的移动规则十分简单:
若蚂蚁在黑格,右转90度,将该格改为白格,并向前移一格;
若蚂蚁在白格,左转90度,将该格改为黑格,并向前移一格。
根据初始状态,用计算机模拟兰顿蚂蚁在第n步行走后所处的位置。
输入数据的第一行是 m n 两个整数(3 < m, n < 100),表示正方形格子的行数和列数。
接下来是 m 行数据。
每行数据为 n 个被空格分开的数字。0 表示白格,1 表示黑格。
接下来是一行数据:x y s k, 其中x y为整数,表示蚂蚁所在行号和列号(行号从上到下增长,列号从左到右增长,都是从0开始编号)。
s 是一个大写字母,表示蚂蚁头的朝向,我们约定:上下左右分别用:UDLR表示。k 表示蚂蚁走的步数。
输出数据为一个空格分开的整数 p q, 分别表示蚂蚁在k步后,所处格子的行号和列号。
*/
#include<iostream>
using namespace std;
void move(int &ant_row, int &ant_col, char &direction, int** block)
{
int flag = block[ant_row][ant_col];
//flag 0:white 1:black
block[ant_row][ant_col] = !block[ant_row][ant_col];
if (flag == 1) //右转90°
{
switch(direction)
{
case 'U':
direction = 'R';
ant_col ++;
break;
case 'R':
direction = 'D';
ant_row++;
break;
case 'D':
direction = 'L';
ant_col--;
break;
case 'L':
direction = 'U';
ant_row--;
}
}
else
{
switch(direction)
{
case 'D':
direction = 'R';
ant_col ++;
break;
case 'L':
direction = 'D';
ant_row++;
break;
case 'U':
direction = 'L';
ant_col--;
break;
case 'R':
direction = 'U';
ant_row--;
break;
}
}
}
int main()
{
int row,col;
cin >> row >> col;
int** block = new int*[row];
for(int i = 0; i < row; i++)
{
block[i] = new int[col];
for(int j = 0; j < col; j++)
{
cin >> block[i][j];
}
}
int ant_row, ant_col, step;
char direction;
cin >> ant_row >> ant_col >> direction >> step;
for(int i = 0; i < step; i++)
{
move(ant_row, ant_col, direction, block);
}
cout << ant_row << " " << ant_col << endl;
return 0;
}