HOnestly, i did not understand the question itself, so i looked up the solution; run my example and figured out how it works.
as always, the idea is to hack the pattern - how the indexes change - and simply code it appropriately.
i drawn this picture:
public class ctci_1_6{
public static void main(String []a){
int image_matrix[][] = {
{1,1,1,1,1,1},
{2,2,2,2,2,2},
{3,3,3,3,3,3},
{4,4,4,4,4,4},
{5,5,5,5,5,5},
{6,6,6,6,6,6}
} ;
print_matrix(image_matrix,6) ;
rotate(image_matrix,6) ;
System.out.println("\n\n AFTER :") ;
print_matrix(image_matrix,6) ;
}
public static void print_matrix(int matrix[][], int n){
for(int i = 0 ; i < n ; i++){
for(int j = 0 ;j < n ; j++){
System.out.print( matrix[i][j] + "\t") ;
}
System.out.println() ;
}
}
public static void rotate(int matrix[][], int n){
for(int layer = 0 ; layer < n/2 ; layer++){
System.out.println("---------------------------------------------------------------------------------------------") ;
int first = layer ;
int last = n - 1 - layer ;
System.out.println("first: " + first + " , last : " + last) ;
for(int i = first; i < last ; i++){
System.out.println("^^^^^") ;
int offset = i - first ;
System.out.println(" offset: " + offset) ;
int top = matrix[first][i] ;
//left -> top
matrix[first][i] = matrix[last - offset][first] ;
System.out.printf("m[%d][%d] = m[%d][%d]\n", first, i, (last - offset), first) ;
//bottom -> left
matrix[last - offset][first] = matrix[last][last - offset] ;
System.out.printf("m[%d][%d] = m[%d][%d]\n", (last - offset), first, last, (last -offset)) ;
//right->bottom
matrix[last][last - offset] = matrix[i][last] ;
System.out.printf("m[%d][%d] = m[%d][%d]\n", last, (last - offset), i, last) ;
//top ->right
matrix[i][last] = top ;
System.out.printf("m[%d][%d] = m[%d][%d]\n", i,last, first,i) ;
}
System.out.println() ;
}
}
}
