private boolean isValid(char[][] board, int row, int col) { int n = board.length; // Check the column for (int i = 0; i < row; i++) { if (board[i][col] == 'Q') { return false; } } // Check the main diagonal for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) { if (board[i][j] == 'Q') { return false; } } // Check the other diagonal for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) { if (board[i][j] == 'Q') { return false; } } return true; }