javaarrayschess

Using 2 input coordinates of the chess board, identify whether or not they crossed each other's path (using queen moves of the chess game)


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();
        }   

    }
}

This is what I only managed to do which is to print the board with 0's and 1's

board:

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

My goal is to code and identify if the 2 queens(which is the two 1's) would cross each other.

I tried a lot of methods but some of them don't work. If you can help me I really appreciate it :)

P.S still learning to code :)


Solution

  • Welcome to StackOverflow :)

    Here is what are you looking for:

    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;
    }
    

    There are these conditions under two queens can see each other: