POJ 1573--Robot Motion
来源:互联网 发布:aim聊天软件 编辑:程序博客网 时间:2024/05/29 19:53
2017-10-07
原题链接
题目大意:
有一个上-下(南-北)方向长为A,左-右(东-西)方向长为B的矩阵,其中每个单元为一个字母(W,N,E或S;分别表示让机器人向左,上,右或下方移动一个单元)。一个机器人从矩阵最北(上)那条边,从左数第X个位置进入矩阵。求其走出矩阵需要的步数,或者陷入一个循环需要的步数以及循环包含的步数。
样例输入:
3 6 5NEESWEWWWESSSNWWWW4 5 1SESWEEESNWNWEENEWSEN0 0 0
样例输出:
10 step(s) to exit3 step(s) before a loop of 8 step(s)
这道题与POJ2632–Crashing Robots类似,不过情况更加简单,只要根据给定的指令进行模拟并记录步数,以及检查是否进入了循环即可。
因为编程时粗心的把判断是否进入了循环的变量“isLoop”定义在了循环体while外面并且没有每次初始化其值,所以WA了几次。贴上一个帮助我找出了BUG的测试数据:
4 4 4WWWSNEESNEESNEEW4 4 1EEESNSWWNEESNWWW1 1 1W
代码:
#include <iostream>#include <cstring>#include <cstdio>#define MAX 15using namespace std;//记录指令: W-0,N-1,E-2,S-3int instructions[MAX][MAX];//记录是否已经过bool isVisited[MAX][MAX];//四个方向对应的坐标变化(W,N,E,S)int dirWE[4] = { 0,-1, 0, 1};int dirNS[4] = {-1, 0, 1, 0};int main() { int A,B,Spos; char Dir[MAX]; while(~scanf("%d%d%d",&A,&B,&Spos)) { if(!A && !B && !Spos) break; //* 对于每次都会使用的变量必须初始化!! * memset(isVisited, false, sizeof(isVisited)); memset(instructions, -1, sizeof(instructions)); bool isLoop = false; //* isLoop的值必须每次初始化 * for(int i = 1; i <= A; i++) { scanf("%s", Dir); for(int j = 1; j <= B; j++) { switch(Dir[j-1]) { case 'W' : instructions[i][j] = 0; break; case 'N' : instructions[i][j] = 1; break; case 'E' : instructions[i][j] = 2; break; case 'S' : instructions[i][j] = 3; break; } } } //用isVisited记录访问情况,用instructions记录已行的步数,用isLoop记录是否有循环 int x = 1; int y = Spos; int steps = 1; while(!isLoop) { //已走出区域 if(x == 0 || x == A+1 || y == 0 || y == B+1) break; else { int ins = instructions[x][y]; isVisited[x][y] = true; //因为每个单元应该只被访问一次,所以可以同时使用存储指令的数组记录步数 instructions[x][y] = steps++; x += dirWE[ins]; y += dirNS[ins]; if(isVisited[x][y]) { isLoop = true; } } } if(isLoop) printf("%d step(s) before a loop of %d step(s)\n",instructions[x][y] - 1, steps - instructions[x][y]); else printf("%d step(s) to exit\n",steps -1); } return 0;}
阅读全文
0 0
- poj 1573 Robot Motion
- Poj 1573 Robot Motion
- poj 1573 Robot Motion
- POJ 1573 - Robot Motion
- poj-1573-Robot Motion
- POJ 1573 Robot Motion
- POJ 1573 Robot Motion
- POJ-1573-Robot Motion
- poj 1573 Robot Motion
- POJ 1573 Robot Motion
- POJ 1573 Robot Motion.
- poj 1573 Robot Motion
- POJ -1573 Robot Motion
- POJ 1573:Robot Motion
- poj 1573 Robot Motion
- poj 1573 Robot Motion
- POJ 1573 Robot Motion
- Robot Motion POJ 1573
- Java冒泡排序
- JZOJsenior2412.【NOI2005】瑰丽华尔兹
- java知识结构图
- CSS cursor 属性
- Hive内部表与外部表(外部表使用场景)
- POJ 1573--Robot Motion
- 【STM32小案例 06 】STM32使用按键驱动L298N电机模块控制电机正反转
- HDU1166 敌兵布阵
- 学习JavaScript数据结构与算法(四)——循环链表
- Remove Duplicates from Sorted Array II
- 看起来像它——图像搜索其实也不难
- 标准IO缓存
- js 时间-date
- 一些oracle相关的链接