题解 | #坐标移动#

坐标移动

http://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29

include

include

include

using namespace std;

/*算法思想:
利用状态机制:
W10;分别对应
1234个个状态,而5代表输入错误,可能是AA10或A或Q等非规则步骤
用direction标记wsad方向,
每遇到一个';'就将上个‘步’更新到坐标
*/

int main()
{
char ch;
int state = 4;
int x = 0, y = 0; //初始坐标
int step = 0;
int direction = 0;
while (cin.get(ch))
{
switch (ch)
{
case 'W':
if (state == 4)
{
state = 1;
direction = 1;
}
else
state = 5;
break;
case 'S':
if (state == 4)
{
state = 1;
direction = 2;
}
else
state = 5;
break;
case 'A':
if (state == 4)
{
state = 1;
direction = 3;
}
else
state = 5;
break;
case 'D':
if (state == 4)
{
state = 1;
direction = 4;
}
else
state = 5;
break;
case ';':
if (state == 2 || state == 3)
{
switch (direction)
{
case 1: y += step; step = 0; break;
case 2: y -= step; step = 0; break;
case 3: x -= step; step = 0; break;
case 4: x += step; step = 0; break;
default:;
}
}
state = 4;
break;
default:
if (ch >= '0' && ch <= '9')
{
if (state == 1)
{
state = 2;
step = ch - '0';
}
else if (state == 2)
{
state = 3;
step = step * 10 + ch - '0';
}
}
else
state = 5;
}
}
if (state == 2 || state == 3)
{
switch (direction)
{
case 1: y += step; step = 0; break;
case 2: y -= step; step = 0; break;
case 3: x -= step; step = 0; break;
case 4: x += step; step = 0; break;
default:;
}
}
cout << x << ',' << y;
return 0;
}

全部评论

相关推荐

龙珠传说:nb,公务员解约不需要支付违约金吧
点赞 评论 收藏
分享
05-16 11:16
已编辑
东华理工大学 Java
牛客73769814...:盲猜几十人小公司,庙小妖风大,咋不叫她去4️⃣呢😁
牛客创作赏金赛
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-27 14:11
很喜欢小米的新车,校招薪资每月22k,攒多久能买?
测试糕手手:别看工资,先看现金流存款。有50W存款以上再考虑,车是消耗品,选适合自己的重要。你有钱就当我没说过
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务