题意:
给出一个由
m×n
m
×
n
个正方形格子组成的矩形平面,正方形格子有黑、白两种。
起初一个蚂蚁在第 x 行、第 y 列(这里的 x 和 y 是从0开始数的,和二维数组的下标一致),朝上下左右中的某一个方向。
然后给出蚂蚁移动一步的规则:
若蚂蚁在黑格,右转90度,将该格改为白格,并向前移一格;
若蚂蚁在白格,左转90度,将该格改为黑格,并向前移一格。
让求蚂蚁移动 k 步后的位置。
思路:
一道模拟题。数据量比较小,所以我们只要按照蚂蚁的移动规则模拟就好啦。
这边处理方向的改变可以用下面的方法:
const char dirc[] = "URDL";
//s 为 int 型,dirc[s]表示当前蚂蚁的方向
//向左转
s = (s-1+4)%4;
//向右转
s = (s+1)%4;
注意:
1. 注意读取方向用 %c 时如果是 scanf(“%d%d%c%d”, ); 读取到的会是空格,所以要写成 scanf(“%d %d %c %d”, )。
代码:
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<stack>
#include<queue>
#include<utility>
#include<vector>
#include<cmath>
#include<set>
#include<map>
#include<iostream>
#include<algorithm>
#include<sstream>
using namespace std;
typedef long long LL;
int m, n;
int G[110][110];
int x, y, k, s;
char S;
const char dirc[] = "URDL";
int main()
{
while(scanf("%d%d", &m, &n) == 2){
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
scanf("%d", &G[i][j]);
}
}
scanf("%d %d %c %d", &x, &y, &S, &k);
for(int i=0; i<4; i++){
if(S == dirc[i]){
s = i; break;
}
}
for(int i=0; i<k; i++){
if(G[x][y]){ //黑格
s = (s+1)%4;
G[x][y] = 0;
}else{ //白格
s = (s-1+4)%4;
G[x][y] = 1;
}
if(s == 0) x--;
else if(s == 1) y++;
else if(s == 2) x++;
else if(s == 3) y--;
//printf("i = %d, (%d,%d)\n", i, x, y);
}
printf("%d %d\n", x, y);
}
return 0;
}