我写了一个代码,可以找到哪个女王位置可以碰撞。是否可以用更少的代码做得更好:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int x1 = scanner.nextInt();
int y1 = scanner.nextInt();
int x2 = scanner.nextInt();
int y2 = scanner.nextInt();
if (x1 == x2 || y1 == y2) {
System.out.println("YES");
}
else if (x1 == x2 || y1 == y2) {
System.out.println("YES");
}
else if (Math.abs(x1 - x2) == Math.abs(y1 - y2)) {
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
if (x1 == x2 || y1 == y2 || (Math.abs(x1 - x2) == Math.abs(y1 - y2))) {
System.out.println("YES");
} else {
System.out.println("NO");
}
else if (x1 == x2 || y1 == y2) {
System.out.println("YES");
}
此条件是多余的。
else if (Math.abs(x1 - x2) == Math.abs(y1 - y2)) {
System.out.println("YES");
}
这可以与前面的条件合并,因为它具有相同的输出。
实现中存在重复检查:第二个if
块与第一个if
块相同。
public boolean checkQueens_v1(int x1, int y1, int x2, int y2) {
if ( (x1 == x2) || (y1 == y2) ) {
return true;
} else if ( Math.abs(x1 - x2) == Math.abs(y1 - y2) ) {
return true;
} else{
return false;
}
}
以下是替代方法:
public boolean checkQueens_v2(int x1, int y1, int x2, int y2) {
int xdiff = x1 - x2;
if ( xdiff == 0 ) {
return true;
}
int ydiff = y1 - y2;
if ( ydiff == 0 ) {
return true;
}
if ( Math.abs(xdiff) == Math.abs(ydiff) ) {
return true;
}
return false;
}
哪个更小/更快很难说:
第一个测试有三个比较和两个减法。 第二个测试有两个与零的比较,一个比较和两个减法。
但是,第二个测试比第一个测试更频繁地进行减法。