When given a square ma开发者_如何学Gotrix, what would be the best way to find all of the possible arrays within it without using more than one element from any row/column in each array?
For example, in a matrix like so:
0 2 3
1 2 3
1 2 0
It would then go through it like this:
And then it would output the following list of arrays:
123
123
023
123
120
020
You can directly map each such array to a permutation of the digits (0 .. size-1). To show you how this works, the permutation (2,1,0)
maps to the 3 coordinates (2,0), (1,1), (0,2)
. The 6 examples you gave are
(2,1,0) (1,2,0) (0,2,1)
(2,0,1) (1,0,2) (0,1,2)
To explain the mapping, lets take the first permutation (2,1,0) --> (2,0), (1,1), (0,2)
. Then, the values you want to use are array[2][0], array[1][1], array[0][2]
So now the question is how to generate each permutation. There are a few algorithms, one of which is implemented in java here: http://www.merriampark.com/perm.htm
精彩评论