Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Lekciq;
- import java.util.Scanner;
- public class FindTheRealQueen {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- // Read the chessboard matrix
- char[][] chessboard = readChessboard(scanner);
- // Find the position of the valid queen
- int[] validQueenPosition = findValidQueenPosition(chessboard);
- // Print the position of the valid queen
- System.out.println(validQueenPosition[0] + " " + validQueenPosition[1]);
- }
- // Method to read the chessboard matrix from the console
- private static char[][] readChessboard(Scanner scanner) {
- char[][] chessboard = new char[8][8];
- for (int i = 0; i < 8; i++) {
- String line = scanner.nextLine();
- for (int j = 0; j < 8; j++) {
- chessboard[i][j] = line.charAt(j * 2);
- }
- }
- return chessboard;
- }
- // Method to find the position of the valid queen
- private static int[] findValidQueenPosition(char[][] chessboard) {
- int[] validQueenPosition = new int[2];
- // Iterate over each cell in the chessboard
- for (int i = 0; i < 8; i++) {
- for (int j = 0; j < 8; j++) {
- if (chessboard[i][j] == 'q') {
- // Check if the current position is valid
- if (isValidQueenPosition(chessboard, i, j)) {
- validQueenPosition[0] = i;
- validQueenPosition[1] = j;
- return validQueenPosition;
- }
- }
- }
- }
- return validQueenPosition;
- }
- // Method to check if the queen at the given position is valid
- private static boolean isValidQueenPosition(char[][] chessboard, int row, int col) {
- // Check horizontally and vertically
- for (int i = 0; i < 8; i++) {
- if (chessboard[row][i] == 'q' && i != col) return false;
- if (chessboard[i][col] == 'q' && i != row) return false;
- }
- // Check diagonally (top-left to bottom-right)
- for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
- if (chessboard[i][j] == 'q') return false;
- }
- for (int i = row + 1, j = col + 1; i < 8 && j < 8; i++, j++) {
- if (chessboard[i][j] == 'q') return false;
- }
- // Check diagonally (top-right to bottom-left)
- for (int i = row - 1, j = col + 1; i >= 0 && j < 8; i--, j++) {
- if (chessboard[i][j] == 'q') return false;
- }
- for (int i = row + 1, j = col - 1; i < 8 && j >= 0; i++, j--) {
- if (chessboard[i][j] == 'q') return false;
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement