POJ1573Robot Motion

本文介绍了一个简单的机器人导航算法,该算法使机器人能在棋盘上根据指定的位置指示进行移动。文章通过C++代码实现了这一过程,并详细展示了如何避免死循环或走出棋盘边界的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

又是一个机器人,按照棋盘相应位置指示走。要么走出棋盘,要么死循环。较简单。
机器人成功走出和循环示意

#include <iostream>
#include <stdio.h>
#include <string.h>
//#define TEST
using namespace std;
char s[20];
char M[20][20];
int path[20][20];
int main()
{
    #ifdef TEST
    freopen("test.txt", "r", stdin);
    #endif // TEST
    int r, c, start;
    while(1)
    {
        scanf("%d %d %d", &r, &c, &start);
        if(r == 0 && c == 0 && start == 0) break;

        memset(M, '\0', sizeof(M));
        memset(path, 0, sizeof(path));
        for(int i = 0; i < r; i++)
        {
            scanf("%s", s);
            for(int j = 0; j < strlen(s); j++)
                M[i][j] = s[j];
        }

        int cx = 0, cy = start-1;
        int cnt = 1;
        path[cx][cy] = cnt;
        while(1)
        {
            int nx, ny;
            switch(M[cx][cy])
            {
                case 'E': nx = cx; ny = cy+1;break;
                case 'S': nx = cx + 1; ny = cy; break;
                case 'W': nx = cx; ny = cy - 1; break;
                case 'N': nx = cx - 1; ny = cy;break;
                default:nx = cx; ny = cy;
            }
            // yue bian jie
            if(nx < 0 || nx == r || ny < 0 || ny == c)
            {
                printf("%d step(s) to exit\n", cnt);
                break;
            }
            else if(path[nx][ny] != 0)
            {
                printf("%d step(s) before a loop of %d step(s)\n", path[nx][ny]-1, path[cx][cy]-path[nx][ny]+1);
                break;
            }
            else
            {
                path[nx][ny] = ++cnt;
                cx = nx;
                cy = ny;
            }
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值