目标
- 达到目标点(lightX, lightY)
- 不越界
- 在能量消耗完之前到达
原程序
import java.util.*;
import java.io.*;
import java.math.*;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
* ---
* Hint: You can use the debug stream to print initialTX and initialTY, if Thor seems not follow your orders.
**/
class Player {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int lightX = in.nextInt(); // the X position of the light of power
int lightY = in.nextInt(); // the Y position of the light of power
int initialTx = in.nextInt(); // Thor's starting X position
int initialTy = in.nextInt(); // Thor's starting Y position
// game loop
while (true) {
int remainingTurns = in.nextInt(); // The remaining amount of turns Thor can move. Do not remove this line.
// Write an action using System.out.println()
// To debug: System.err.println("Debug messages...");
// A single line providing the move to be made: N NE E SE S SW W or NW
System.out.println(“SW”);
}
}
}
思路
解决方法很简单:只需判断方位拼接字符串就可以了。因为斜向的方位表示:"NE NW SE SW ",是以“N”,“S”开头的,因此先判断"Y"轴的方位,再判断“X”轴。
// game loop
while (true) {
int remainingTurns = in.nextInt(); // The remaining amount of turns Thor can move. Do not remove this line.
String a = "";
if(initialTy < lightY){
a = "S";
}
else if(initialTy > lightY){
a = "N";
}
if(initialTx < lightX){
a += "E";
}
else if(initialTx > lightX){
a += "W";
}
// Write an action using System.out.println()
// To debug: System.err.println("Debug messages...");
// A single line providing the move to be made: N NE E SE S SW W or NW
System.out.println(a);
}
出错
不过很遗憾,上面代码只能通过单方向移动案例,不能通过需斜对角移动案例。在思路没有错误的情况下,我们去查看输出数据:
数据显示,Thor在最后第二次移动时,Y轴的坐标已经与目标Y坐标相等,但Thor依然“勇往直前”。这就是问题所在。
修正
回过头去查看代码,我们发现在while循环中,Thor的坐标从未发送改变,而输出数据“欺骗”了我们,让我们以为变化了(浪费我时间去检查,angry)。
因此我们需要在代码中对Thor的坐标进行操作:
while (true) {
int remainingTurns = in.nextInt(); // The remaining amount of turns Thor can move. Do not remove this line.
String a = "";
if(initialTy < lightY){
initialTy+=1;
a = "S";
}
else if(initialTy > lightY){
initialTy-=1;
a = "N";
}
if(initialTx < lightX){
initialTx +=1;
a += "E";
}
else if(initialTx > lightX){
initialTx-=1;
a += "W";
}
// Write an action using System.out.println()
// To debug: System.err.println("Debug messages...");
// A single line providing the move to be made: N NE E SE S SW W or NW
System.out.println(a);
}
此时,所有案例通过
结语
不要尝试枚举所有情况!没有意义