POJ 1573 Robot Motion 水模拟

本文通过C++实现了一个迷宫路径寻找算法,该算法能够计算从起点到终点的步数,或者在遇到循环路径时输出循环前的步数及循环路径长度。通过对迷宫格子的方向转换,使用二维数组记录每个位置的方向,进而模拟行走过程。

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

step后面的s不用讨论,~~~~不然wa.......


#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cmath>

using namespace std;
//0,1,2,3,N,W,S,E

int map[15][15];
char a[15][15];

int dx[] = {-1,0,1,0};
int dy[] = {0,-1,0,1};


int main()
{
    int n, m, k;
    int i, j;
    while(cin >> n >> m >> k){
        memset(map,0,sizeof(map));
        memset(a,0,sizeof(a));
        if(n==0&&m==0&&k==0) break;
        for(i = 0;i < n;i++){
            cin >> a[i];
        }
        for(i = 1;i <= n;i++){
            for(j = 1;j <= m;j++){
                if(a[i-1][j-1] == 'N'){
                    map[i][j] = 0;
                }else if(a[i-1][j-1] == 'W'){
                    map[i][j] = 1;
                }else if(a[i-1][j-1] == 'S'){
                    map[i][j] = 2;
                }else if(a[i-1][j-1] == 'E'){
                    map[i][j] = 3;
                }
            }
        }
        int x = 1, y = k;
        int cnt[15][15];
        memset(cnt,0,sizeof(cnt));
        cnt[x][y] = 1;
        int xx =1, yy = k;
        while(1){
            x = xx;
            y = yy;
            xx = x+dx[map[x][y]];
            yy = y+dy[map[x][y]];
            if(xx>=1&&xx<=n&&yy>=1&&yy<=m){
                if(cnt[xx][yy] == 0){
                    cnt[xx][yy] = cnt[x][y] + 1;
                }else {
                    int tt = cnt[x][y] - cnt[xx][yy] +1;
                    printf("%d step(s) before a loop of %d step(s)\n",  cnt[xx][yy]-1, tt);
                    break;
                }
            }else {
                printf("%d step(s) to exit\n", cnt[x][y]);
                break;
            }
        }
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值