使用棋盘的2个输入坐标,识别它们是否交叉了彼此的路径(使用国际象棋游戏的皇后走法)

问题描述 投票:0回答:2
class Board 
{
     public static void main(String args[]) 
    {

        int i, j;
        int x1 = 0, y1 = 0;
        int x2 = 0, y2 = 0;
        int[][] board = new int[8][8];

        x1 = Integer.parseInt(args[0]); 
        y1 = Integer.parseInt(args[1]); 
        x2 = Integer.parseInt(args[2]); 
        y2 = Integer.parseInt(args[3]); 


        // initialize the board to 0's
        for (i = 0; i < 8; i++)
            for (j = 0; j < 8; j++)
                board[i][j] = 0;

        board[x1][y1] = 1;      
        board[x2][y2] = 1;      

        for (i = 0; i < 8; i++) 
        {
            for (j = 0; j < 8; j++) 
            {
                System.out.print(board[i][j]+" ");
            }
            System.out.println();
        }   

    }
}

这是我唯一能做的就是用0和1打印棋盘

板:

0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1

我的目标是编码并确定 2 个皇后(即两个 1)是否会相互交叉。

我尝试了很多方法,但有些方法不起作用。 如果你能帮助我,我真的很感激:)

P.S 仍在学习编码:)

java arrays chess
2个回答
4
投票

欢迎来到 StackOverflow :)

这就是您要找的:

public static boolean twoQueensSeeEachOther(int x1, int y1, int x2, int y2) {
    if (x1 == x2 && y1 == y2) {
        return true;                                // One has picked another
    }
    if (x1 == x2 || y1 == y2) {
        return true;                                // Row or column
    }
    if (Math.abs(x1 - x2) == Math.abs(y1 - y2)) {
        return true;                                // Diagonal
    }
    return false;
}

两个女王可以看到对方有这些条件:

  • 如果他们都在同一个地方,则一个选择另一个

  • 如果它们共享同一轴(x 或 y),它们会看到对方,因为它们可以像车一样移动。如果它们的

    x
    y
    位置相同,则满足此条件。

  • 如果他们共享相同的对角线,他们会看到对方,因为他们可以作为主教移动。如果轴之间的差异相等,则满足此条件。示例:

    • 黑皇后在
      [2,5]
      位置,白皇后在
      [4,3]
      位置。
    • x
      轴之间的差异为
      xDiff = abs(2 - 4) = 2
    • y
      轴之间的差异为
      yDiff = abs(5 - 3) = 2
    • 两者的差异是相等的 - 他们在对角线上看到对方。

0
投票
import java.util.Scanner;
class Main {

public static void main(String[] args){
    Scanner scanner = new Scanner(System.in);
        int x1 = scanner.nextByte();
        int y1 = scanner.nextByte();
        int x2 = scanner.nextByte();
        int y2 = scanner.nextByte();
        boolean sameRow = y1 == y2;
        boolean sameColumn = x1 == x2;
        boolean canAttack;

        if (sameRow || sameColumn) {
            canAttack = true;
        } else {
            canAttack = Math.abs(x1 - x2) == Math.abs(y1 - y2);
        }
        System.out.println(canAttack ? "YES" : "NO");

}
}
© www.soinside.com 2019 - 2024. All rights reserved.