【刷题】蓝桥杯——兰顿蚂蚁——C++
发布日期:2021-04-30 21:00:55 浏览次数:155 分类:精选文章

本文共 1907 字,大约阅读时间需要 6 分钟。

为了解决这个问题,我们需要模拟兰顿蚂蚁在给定网格中的移动过程。兰顿蚂蚁的移动规则是:如果它处于黑色格子,右转90度并移动到下一个白色格子;如果它处于白色格子,则左转90度并移动到下一个黑色格子。我们需要根据初始状态,计算蚂蚁在给定步数后的位置。

方法思路

  • 初始化网格和蚂蚁的位置:读取输入数据,初始化网格,并将蚂蚁的初始位置和方向记录下来。
  • 模拟蚂蚁的移动:循环移动蚂蚁,根据当前格子的颜色决定转向,并更新网格颜色和蚂蚁的位置。
  • 处理方向转换:使用方向列表来处理蚂蚁的转向,确保方向转换正确。
  • 计算最终位置:在完成给定步数的移动后,输出蚂蚁的最终位置。
  • 解决代码

    #include 
    #include
    using namespace std;int main() { int m, n; cin >> m >> n; int a[m][n]; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { int b; cin >> b; a[i][j] = b; } } int x, y; char s; int k; cin >> x >> y >> s >> k; int current_row = x; int current_col = y; int dir_index = 0; if (s == 'U') dir_index = 0; else if (s == 'D') dir_index = 2; else if (s == 'L') dir_index = 3; else dir_index = 1; // 'R' for (int steps = 0; steps < k; ++steps) { int color = a[current_row][current_col]; if (color == 1) { // Right turn dir_index = (dir_index + 1) % 4; a[current_row][current_col] = 0; } else { // Left turn dir_index = (dir_index - 1 + 4) % 4; // Avoid negative index a[current_row][current_col] = 1; } // Move according to direction switch (dir_index) { case 0: // U current_row--; break; case 1: // R current_col++; break; case 2: // D current_row++; break; case 3: // L current_col--; break; } } cout << current_row << ' ' << current_col << endl; return 0;}

    代码解释

  • 读取输入和初始化网格:首先读取网格的行数和列数,然后读取网格的颜色数据。接着读取蚂蚁的初始位置、方向和步数。
  • 初始化方向索引:根据蚂蚁的初始方向,确定初始的方向索引。
  • 循环模拟移动:循环移动蚂蚁,根据当前格子的颜色决定转向,并更新网格颜色和蚂蚁的位置。
  • 处理方向转换:使用方向索引来处理转向,确保方向转换正确。
  • 输出最终位置:在完成给定步数的移动后,输出蚂蚁的最终位置。
  • 通过这种方法,我们可以准确地模拟兰顿蚂蚁的移动过程,并得到其在给定步数后的最终位置。

    上一篇:LeetCode笔记:原地修改数组
    下一篇:Redis学习笔记_03:事务+Jedis+SpringBoot整合

    发表评论

    最新留言

    很好
    [***.229.124.182]2026年06月16日 02时27分06秒