移动

逐字符模拟机器人移动,并在每一步只接受仍处于正方形场地内的新位置。

OJ: shumeng

题目 ID: CSP202412A

难度:入门

标签:模拟

日期: 2026-07-31 16:21

形式化题目

机器人位于 n×nn \times n 的方格场地内。fblr 分别表示向上、向下、向左、向右移动一格;若目标位置越出场地边界,本次指令无效,位置保持不变。

对每个起点和指令串,输出最终位置。

思路

按指令串从左到右逐条模拟即可。每步先根据当前指令算出候选位置,再检查两个坐标是否都在 [1,n][1, n] 内:合法则更新位置,越界则忽略该指令。

关键点在于每一步移动后都要判断边界,而不是等整串指令执行完再检查。

代码

cpp
/**
 * Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
 * rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
 * rainboy的学习导航网站: https://idx.roj.ac.cn
 * create_at: 2026-07-31 16:21
 * update_at: 2026-08-17 22:39
 */
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, k;
    cin >> n >> k;
    while (k--) {
        int x, y;
        string commands;
        cin >> x >> y >> commands;

        // 逐条指令移动:f 上、b 下、l 左、r 右
        for (int i = 0; i < (int)commands.size(); i++) {
            int next_x = x;
            int next_y = y;
            if (commands[i] == 'f') next_y++;
            else if (commands[i] == 'b') next_y--;
            else if (commands[i] == 'l') next_x--;
            else if (commands[i] == 'r') next_x++;
            // 越界则本次指令无效,位置保持不变
            if (1 <= next_x && next_x <= n && 1 <= next_y && next_y <= n) {
                x = next_x;
                y = next_y;
            }
        }
        cout << x << ' ' << y << '\n';
    }

    return 0;
}

复杂度

设单条指令串长度为 LLkk 组数据。

  • 时间:每个字符处理一次,O(kL)O(kL)
  • 空间:O(1)O(1) 额外空间。

总结

纯模拟题,注意越界指令丢弃而非回退即可。把“算候选位置 → 判断合法性 → 更新”写成清晰的三步,就不容易在边界判断上出错。