java參考答案
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static int same(List<String> list, int x, int y) {
String command = list.get(y);
if (command.equals("LEFT")) {
x -= 1;
} else if (command.equals("RIGHT")) {
x += 1;
} else if (command.contains("SAME AS")) {
int index = Integer.parseInt(command.substring(8)) - 1;
x = same(list, x, index);
}
return x;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = sc.nextInt();
sc.nextLine();
for (int i = 0; i < count; i++) {
int code_count = sc.nextInt();
sc.nextLine();
List<String> list = new ArrayList<>();
for (int n = 0; n < code_count; n++) {
String command = sc.nextLine();
list.add(command);
}
int x = 0;
for (int p = 0; p < list.size(); p++) {
String command = list.get(p);
if (command.equals("LEFT")) {
x -= 1;
} else if (command.equals("RIGHT")) {
x += 1;
} else if (command.contains("SAME AS")) {
int index = Integer.parseInt(command.substring(8)) - 1;
x = same(list, x, index);
}
}
System.out.println(x);
}
sc.close();
}
}