A band matrix is a matrix whose non-zero entries fall within a diagonal band, consisting of the main diagonal and zero or more diagonals on either side of it. (The main diagonal of a matrix consists of all entries \$a_{i,j}\$ for which \$i=j\$.) For this challenge, we will only be considering square matrices.
For example, given this matrix:
1 2 0 0
3 4 5 0
0 6 0 7
0 0 8 9
this is the band:
1 2
3 4 5
6 0 7
8 9
The main diagonal (1 4 0 9
) and the diagonals above it (2 5 7
) and below it (3 6 8
) are the only places non-zero elements are found; all other elements are zero. (Some of the elements in the band may also be zero.)
The bandwidth of the matrix is the smallest number \$k\$ such that all non-zero elements are contained within a band consisting of the main diagonal, \$k\$ diagonals above it, and \$k\$ diagonals below it. The bandwidth of the above matrix is 1: all non-zero elements fall within the main diagonal, the one diagonal above it, or the one diagonal below it. For another example:
1 1 0 0
1 1 1 0
1 1 1 1
0 1 1 1
The bandwidth of this matrix is 2, because it takes two diagonals above and below the main diagonal to catch all non-zero elements:
1 1 0
1 1 1 0
1 1 1 1
1 1 1
Note that for the purposes of this challenge, the band must extend the same distance on either side of the main diagonal, which is why the diagonal 0 0
is included above.
Mathematically, the bandwidth is the smallest number \$k\$ such that for every entry \$a_{i,j}\$ in the matrix, \$a_{i,j} = 0\$ if \$|i-j|>k\$.
Challenge
Given a square matrix containing nonnegative integers, output its bandwidth.
The matrix will always have at least one nonzero entry.
This is code-golf: make your code (measured in bytes) as short as possible.
Test cases
1
=>
0
1 0 0
0 1 0
0 0 1
=>
0
1 2 0 0
3 4 5 0
0 6 0 7
0 0 8 9
=>
1
1 1 0 0
1 1 1 0
1 1 1 1
0 1 1 1
=>
2
16 18 8
6 14 22
20 10 12
=>
2
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
=>
3