Rearrange the numbers in a matrix using the minimum local movement implied by repeated adjacent swaps, and report the required total effort.
You are given an matrix containing integers. By repeatedly swapping adjacent elements in rows and columns, you want to transform the matrix into a state where the values are arranged in nondecreasing order when read row by row.
Your task is to determine the minimum total number of adjacent swaps needed to achieve this arrangement. If the matrix can already be considered sorted in this reading order, the answer is $0$.
Think of the matrix entries as a flattened sequence in row-major order. The goal is to measure how much local movement is needed to place the elements into sorted order.
Example 1
Input
2 3 4 1 3 2 6 5
Output
5
Explanation
Flattening gives [4,1,3,2,6,5]. Sorting to [1,2,3,4,5,6] requires a minimum of 5 adjacent swaps, which equals the inversion count of the flattened sequence when duplicates are handled consistently.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.