Matrices with Maximum Row and Column Sums

2026-11-05

Table of Contents

Nerd Sniped$^2$

While being nerd-sniped about the "N-M Balancers" problem, I got nerd-sniped further and wanted to know how many (directed unweighted) graphs there are with N nodes that have no more than two edges coming into or out of any node, no duplicate edges, and no self-edges. That's a bit tricky but since graphs (without duplicate edges) can be represented as a matrix, a slightly easier (and not necessarily the easiest) similar question is How many NxN matrices, with 0, 1, or 2 in each cell, have no row or column with sum > 2?.

Luckily I came across A049088 in the Online Encyclopedia of Integer Sequences, which was great for 3 reasons: First, it very quickly let me know that the number of matrices was likely large because A049088 appears to grow super exponentially. Second, it gave a nice reference for the correct answer of the first terms. Finally, it led to related sequences.

That got me hooked on solving an even more generalized problem: How many NxM matrices, with nonnegative integers in each cell, have no row or column with sum > K?

Existing Code

A049088 is just the diagonal of A131235, which looks at NxM matrices, not just NxN. Aaaaand it happens to include some maple and mathematica code for generating the terms!

A131235 := proc(m, n)
   exp((x*y*(3-x*y)+(x+y)*(2-x*y))/2/(1-x*y))/sqrt(1-x*y) ;
   coeftayl(%, y=0, n)*n!;
   coeftayl(%, x=0, m)*m! ;
end proc: # R. J. Mathar, Mar 20 2018
T[n_, k_] := Module[{ex}, ex = Exp[(x*y*(3 - x*y) + (x + y)*(2 - x*y))/2/(1 - x*y)]/Sqrt[1 - x*y]; SeriesCoefficient[ex, {y, 0, k}]*k! // SeriesCoefficient[#, {x, 0, n}]*n!&];
Table[T[n - k, k], {n, 0, 10}, {k, 0, n}] // Flatten (* Jean-François Alcover, Sep 14 2023, after R. J. Mathar *)

Unfortunately this code (or at least a version of it translated to Python using the sympy library) is slow and beyond my understanding.

New Code

Luckily, this is a fairly straightforward recursive problem to implement inefficiently and not too hard to optimize via careful caching.

Slow Version

import math


def matrices_with_max_sums(
        col_max_sums: tuple[int, ...], 
        row_max_sums: tuple[int, ...], 
        col: int=0) -> int:
    if not row_max_sums:
        return 1
    if col >= len(col_max_sums):
        return matrices_with_max_sums(col_max_sums, row_max_sums[1:], 0)
    return sum(
        matrices_with_max_sums(
            col_max_sums[:col] + (col_max_sums[col] - delta,) + col_max_sums[col + 1:], 
            (row_max_sums[0] - delta,) + row_max_sums[1:], 
            col + 1)
        for delta in range(min(col_max_sums[col], row_max_sums[0]) + 1)
    )


def A131235_T(n, k):
    return matrices_with_max_sums(tuple([2]*(n - k)), tuple([2]*k))


def A131235(n):
    row = math.ceil((math.sqrt(8 * n + 1) - 1) / 2) - 1
    col = n - row * (row + 1) // 2
    return A131235_T(row, col)


for n in range(7):
    for k in range(n + 1):
        print(A131235_T(n, k), end=' ')
    print()

"""
The output matches A131235 as expected:
1 
1 1 
1 3 1 
1 6 6 1 
1 10 26 10 1 
1 15 79 79 15 1 
1 21 189 451 189 21 1
"""

The matrices_with_max_sums function above works by keeping track of the remaining "budget" or max values for each row and column. Each row is processed from col == 0 to col == len(col_max_sums) - 1. Once a row is fully processed it is no longer needed and so it is discarded via if col >= len(col_max_sums): return matrices_with_max_sums(col_max_sums, row_max_sums[1:], 0).

Optimized/Cached Version

import math
import sys
from typing import Iterable, Iterator


sys.setrecursionlimit(999_999)


MWMS_CACHE = {}
def _matrices_with_max_sums(
        col_max_sums: tuple[int, ...], 
        row_max_sums: tuple[int, ...], 
        col: int) -> int:
    if col and col_max_sums[col - 1] == 0:
        col -= 1
        col_max_sums = col_max_sums[:col] + col_max_sums[col + 1:]
    # assert 0 not in col_max_sums
    if not row_max_sums or not col_max_sums:
        return 1
    if col >= len(col_max_sums) or not row_max_sums[0]:
        return _matrices_with_max_sums(col_max_sums, row_max_sums[1:], 0)

    col_max_sums = tuple(sorted(col_max_sums[:col])) + tuple(sorted(col_max_sums[col:]))
    if col == 0:
        # assert row_max_sums == tuple(sorted(row_max_sums))
        if len(row_max_sums) < len(col_max_sums):
            row_max_sums, col_max_sums = col_max_sums, row_max_sums
        elif len(row_max_sums) == len(col_max_sums) and row_max_sums > col_max_sums:
            row_max_sums, col_max_sums = col_max_sums, row_max_sums
    
    cache_key = (col_max_sums, row_max_sums, col)
    if not cache_key in MWMS_CACHE:
        MWMS_CACHE[cache_key] = sum(
            _matrices_with_max_sums(
                col_max_sums[:col] + (col_max_sums[col] - delta,) + col_max_sums[col + 1:], 
                (row_max_sums[0] - delta,) + row_max_sums[1:], 
                col + 1)
            for delta in range(min(col_max_sums[col], row_max_sums[0]) + 1)
        )
    return MWMS_CACHE[cache_key]


def matrices_with_max_sums(
        col_max_sums: Iterable[int] | Iterator[int], 
        row_max_sums: Iterable[int] | Iterator[int]) -> int:
    return _matrices_with_max_sums(tuple(sorted(col_max_sums)), tuple(sorted(row_max_sums)), 0)


def A131235_T(n, k):
    return matrices_with_max_sums([2]*(n - k), [2]*k)


def A131235(n):
    row = math.ceil((math.sqrt(8 * n + 1) - 1) / 2) - 1
    col = n - row * (row + 1) // 2
    return A131235_T(row, col)


def A049088(n):
    return matrices_with_max_sums([2]*n, [2]*n)


def A131236(n):
    return sum(A131235_T(n, m) for m in range(n + 1))


for n in range(60):
    for k in range(n + 1):
        print(A131235_T(n, k), end=' ')
    print()
print(len(MWMS_CACHE))  # Prints 196837

The code above runs in just over 2 seconds on my 2013 laptop and only needed to cache less than 200k entries.

The Best* Caching

I think the most interesting part about the caching is how sensitive it is to the specific ways that col_max_sums and row_max_sums are canonicalized/transformed. There's nothing special about any particular row or column except it's *_max_sums constraint so we're really free to swap any of the columns with any other column or any row with any other row. Furthermore we can even swap all of the columns with all of the rows (transposing the matrices we're counting without affecting the total count).

Optimizations like removing any zeroes once they appear makes the cache hit much more likely. For example, col_max_sums == (0, 0, 1, 2) is the same as (2, 1) or even (0, 1, 0, 2, 0, 0). The same applies for row_max_sums.

If we call this function multiple times with different parameters, the likelihood of getting a cache hit versus a cache miss entirely depends on how we order col_max_sums and row_max_sums. In fact, there might not even be a predictable way that we want to canonicalize the inputs. If we have many entries in the cache with row_max_sums = (2, 2) and we're currently inside of the matrices_with_max_sums function with row_max_sums = (2, 3, 2), then we probably want to process the 3 row first/now, so we can take advantage of the subproblem (row_max_sums = (2, 2)) being in the cache.

Maybe this means to take full advantage of the cache we would actually have to do some kind of upfront search for the 'shortest path' between our current inputs and the set of entries in our cache that we can reach. I didn't pursue that though I think it would be interesting to do.

Measuring Empirically

With some intrusive modifications to the code we can check how sorting row_max_sums differently or swapping row_max_sums and col_max_sums under different circumstances affects the cache size (and hit rate).

We'll try the follownig changes:

# Replace tuple(sorted(row_max_sums)) with one of the following:
ROW_SORTS = {
    'yes': lambda row_max_sums: tuple(sorted(row_max_sums)),
    'yesX': lambda row_max_sums: row_max_sums[:1] + tuple(sorted(row_max_sums[1:])),
    'no': lambda row_max_sums: row_max_sums,
    'reverse': lambda row_max_sums: tuple(sorted(row_max_sums, reverse=True)),
    'reverseX': lambda row_max_sums: row_max_sums[:1] + tuple(sorted(row_max_sums[1:], reverse=True)),
}
# Replace tuple(sorted(col_max_sums[:col])) + tuple(sorted(col_max_sums[col:])) with one of the following:
COL_SORTS = {
    'yes': lambda col_max_sums, col: tuple(sorted(col_max_sums[:col])) + tuple(sorted(col_max_sums[col:])),
    'yesX': lambda col_max_sums, col: () if not col_max_sums else tuple(sorted(col_max_sums[:col])) + (col_max_sums[col],) + tuple(sorted(col_max_sums[col + 1:])),
    'no': lambda col_max_sums, col: col_max_sums,
    'reverse': lambda col_max_sums, col: tuple(sorted(col_max_sums[:col], reverse=True)) + tuple(sorted(col_max_sums[col:], reverse=True)),
    'reverseX': lambda col_max_sums, col: () if not col_max_sums else tuple(sorted(col_max_sums[:col], reverse=True)) + (col_max_sums[col],) + tuple(sorted(col_max_sums[col + 1:], reverse=True)),
}
# Replace the code that controls on row_max_sums col_max_sums or swapped (below)
# with different "value getters": identity vs sum vs len 
# and comparison operators: less than vs greater than
# Note that we replace 2 "value getters" and 2 comparison operators since there's a tiebreaker
# if len(row_max_sums) < len(col_max_sums):
#     row_max_sums, col_max_sums = col_max_sums, row_max_sums
# elif len(row_max_sums) == len(col_max_sums) and row_max_sums > col_max_sums:
#     row_max_sums, col_max_sums = col_max_sums, row_max_sums
RCS_GETS = {
    'identity': lambda x: x,
    'sum': sum,
    'len': len,
}
RCS_CMPS = {
    'lt': operator.lt,
    'gt': operator.gt,
}

In total, there are 5 ways to sort (or not sort) row_max_sums, 5 ways to sort/not col_max_sums, 3 value getters, 2 comparison operators, 3-1 tiebreaker value getters, and 2 tiebreaker comparison operators: 5 * 5 * 3 * 2 * 2 * 2 = 600 possibilities in total.

Below is a chart showing the cache size after calculating the n-th row of A131235 under a select few different circumstances. Based on the chart, the best way to calculate the first 20 rows of A131235, the best configuration is to sort row_max_sums and col_max_sums and only swap them when len(row_max_sums) < len(col_max_sums) or len(row_max_sums) == len(col_max_sums) and row_max_sums > col_max_sums. This corresponds to the "yes_yes_len_lt_identity_gt" in the chart.

Chart of cache size vs n

Here's the code that implements this and generates the data for the chart above.

I feel relatively confident that this is the best way to cache... but not 100% confident. If you have ideas on how to improve the caching, I'd love to listen!

COMMENTS

You can comment on this post by replying to infosec.exchange/@mikelmcdaniel/117630480265218666 on Mastodon.

Don't have a Mastodon account? JoinMastodon.org.