题解 | #坐标移动#
坐标移动
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;
}