“Cut” a matrix of integers on the line where the sum of the absolute differences of “severed” neighbors is the least.
Example
Consider this matrix:
1 2 -4
5 -1 3
2 -2 0
It can be cut in 4 places, here shown by lines lettered A
–D
:
A B
╷ ╷
1 ╎ 2 ╎ -4
C ---╎----╎----
5 ╎ -1 ╎ 3
D ---╎----╎----
2 ╎ -2 ╎ 0
╵ ╵
The cost to cut on a line is the sum of the absolute differences of the numbers opposing each other on that line. For example, cutting on B
would cost \$\lvert 2--4\rvert+\lvert-1-3\rvert+\lvert-2-0\rvert=12\$.
Your task, however, is to find the cheapest cut, which in this case is D
: \$\lvert 5-2\rvert+\lvert-1- -2\rvert+\lvert 3-0\rvert=7\$.
Input
The input will be a 2-D matrix of integers in any reasonable format. It will always have at least two rows and at least two columns and might not be square.
Output
The output may be one of the following:
- Two separate matrices representing the “pieces” of the original matrix after the cut, in any reasonable format. The two matrices may be in either order but must be the same shape as they were in the original matrix.
- An expression representing where the cut is, e.g.
D
as above or the equivalent index 3 (0-based) or 4 (1-based), in any reasonable format. You may invent your own indexing scheme but it must be described in your answer and be consistent.
Rules
If more two or more cuts are tied for lowest cost, you may either output any one of them, or all of them.
Default I/O rules and standard rules apply. Standard loopholes are forbidden.
This is code-golf; shortest solution in bytes wins.
Test cases
Input
8 1 2 -3
6 -2 -7 -4
-1 -6 -9 3
Output
x
8 1 ╎ 2 -1
6 -2 ╎ -7 -4
-1 -6 ╎ -9 3
╵
Input
2 -2 1
8 7 -7
-9 5 -3
0 -8 6
Output
2 -2 1
x---------
8 7 -7
-9 5 -3
0 -8 6
and/or
2 -2 1
8 7 -7
x---------
-9 5 -3
0 -8 6