poj 1573 Robot Motion

题意:给出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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值