您的位置:首页 > 其它

poj 1573 Robot Motion

2016-10-11 00:13 232 查看
题意:给出3个数字,分别为指令矩阵的行数、列数和机器人进入矩阵时所在列。机器人每次都从矩阵的北边进入矩阵,矩阵中的字符指代机器人的移动方向,输出机器人在矩阵中的移动步数;如果机器人进入死循环,输出进入死循环前的移动步数和死循环的大小。

分析:模拟机器人在矩阵走,如果某个方格经过了两次,说明进入了死循环。

#include<cstdio>
#include<cstring>
using namespace std;
const int MAX = 101;
const int dx[] = {0, -1, 0, 1}, dy[] = {-1, 0, 1, 0};
int dir[MAX][MAX], cnt[MAX][MAX];

int main() {
int n, m, s;
while(scanf("%d%d%d", &n, &m, &s) != EOF) {
if(!n && !m && !s) { return 0; }
for(int i = 1; i <= n; i++) {
getchar();
for(int j = 1; j <= m; j++) {
char ch = getchar();
if(ch == 'W') { dir[i][j] = 0; }
else if(ch == 'N') { dir[i][j] = 1; }
else if(ch == 'E') { dir[i][j] = 2; }
else { dir[i][j] = 3; }
}
}
int x = 1, y = s, step = 0, loop = 0, d;
memset(cnt, 0, sizeof(cnt));
while(x > 0 && x <= n && y > 0 && y <= m && cnt[x][y] != 2) {
step++;
loop += cnt[x][y];
cnt[x][y]++;
d = dir[x][y];
x += dx[d];
y += dy[d];
}
if(!loop) { printf("%d step(s) to exit\n", step); }
else { printf("%d step(s) before a loop of %d step(s)\n", step - loop * 2, loop); }
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: