考虑模拟,将"WASD"做一一映射,一个比较简单的方式是给出x和y的前进的方向数组,往左转对应的方向下标+1,往右就-1,最后输出位置即可。
Java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
int[][] ne = {{0, 1}, {-1, 0}, {0, -1}, {1, 0}};
int x = 0, y = 0, d = 0;
for (char c : s.toCharArray()) {
switch (c) {
case 'W':
x += ne[d][0];
y += ne[d][1];
break;
case 'A':
d = (d + 1) % 4;
break;
case 'D':
d = (d + 3) % 4;
break;
default:
break;
}
}
System.out.println(x + " " + y);
}
}
C++
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
cin >> s;
int ne[4][2] = {{0, 1}, {-1, 0}, {0, -1}, {1, 0}};
int x = 0, y = 0, d = 0;
for (char c : s) {
if (c == 'W') {
x += ne[d][0];
y += ne[d][1];
} else if (c == 'A') {
d = (d + 1) % 4;
} else if (c == 'D') {
d = (d + 3) % 4;
}
}
cout << x << " " << y << endl;
return 0;
}
Python
s = input()
ne = [[0, 1], [-1, 0], [0, -1], [1, 0]]
x, y, d = 0, 0, 0
for c in s:
if c == 'W':
x, y = x + ne[d][0], y + ne[d][1]
elif c == 'A':
d = (d + 1) % 4
elif c == 'D':
d = (d + 3) % 4
else:
continue
print(x, y)
会员可通过查看《已通过》的提交记录来查看其他语言哦~
小红昨晚喝醉了,走路开始疯狂把摆,方向也分不清了。假设他所在的地方是一个二维平面,一开始它位于坐标为(0.0)的地方,并且面朝北方即y轴正方向。W表示小红向前走,A表示小红把当前方向向左转90度,D表示小红把方向向右转90度,S表示小红呆在原地。
给出一个字符串表示小红的酒后行为方式,你能告诉他走完后它位于哪个坐标点吗?
输入仅有一行,一个字符串S(1<=∣S∣<=105),并且仅 有'W', 'S','A','D' 这四种字符表示小红的行为方式。
输出仅有一行,坐标位置x和y用空格分开,表示小红的最终位置。
输入
WAW
输出
-1 1