I have following 5x5 matrix:
11 21 31 41 51
12 22 32 42 52
13 23 33 43 53
14 24 34 44 54
15 25 35 45 55
Now I want to reflect that matrix and get following result:
55 54 53 52 51
45 44 43 42 41
35 34 33 32 31
25 24 23 22 21
15 14 13 12 11
The original matrix is represented by an 2D-array matrix[ row ][ column ]. So the idea is to swap the values.
My strategy is:
(1,1) with (5,5)
(1,2) with (4,5)
(1,3) with (3,5)
(1,4) with (2,5)
and
(2,1) with (5,4)
(2,2) with (4,4)
(2,3) with (3,4)
(2,4) with (2,4)
...
Here is my code:
for(int i = 0;开发者_开发技巧 i < 5; i++){
for(int k = 0; k < 4; k++){
int f = matrix[i][k];
int s = matrix[4-k][4-i];
matrix[i][k] = s;
matrix[4-k][4-i] = f;
}
}
The code doesn't work. Any ideas?
You are swapping the elements twice. You need swap only the upper(or lower) diagonal elements. You can do:
int size = arr.length;
for(int i=0;i<size;i++){
for(int j=0;j<size-i;j++){
int tmp = arr[i][j];
arr[i][j] = arr[size-j-1][size-i-1];
arr[size-j-1][size-i-1] = tmp;
}
}
Code In Action
You can use a copy of the same matrix, to be able to store the values in the new matrix2. (martix != matrix2)
is true.
Now I use this code to reverse your matrix:
for(int i=0; i<5; i++) {
for(int j=0; j<5; j++) {
matrix[i][j] = matrix2[4-j][4-i];
}
}
I decided I'd like to see this as a foreach loop so I did the following:
int bound = matrix.size - 1;
for (int[] row : matrix) {
for (int theint : row) {
//get current position; price of foreach
cury = matrix.indexOf(row);
curx = row.indexOf(theint);
//verify that we're above swap line
if (cury + curx < bound) {
//calculate reflected position
def newx = bound - curx;
def newy = bound - cury;
//do swap
def tmp = matrix[newx][newy];
matrix[newx][newy] = matrix[cury][curx];
matrix[cury][curx] = tmp;
}
}
}
Don't know why but I felt like it was a little clearer than the ones using i, j, k, etc… I believe @codaddict's answer works, though.
精彩评论