Welcome Message

Hi, welcome to my website. This is a place where you can get all the questions, puzzles, algorithms asked in interviews and their solutions. Feel free to contact me if you have any queries / suggestions and please leave your valuable comments.. Thanks for visiting -Pragya.

December 28, 2009

Program to rotate a Matrix

public class RotateMatrix {

//~ Methods --------------------------------------------------------------------------------------------------------

/**
* @param args
*/
public static void main(String[] args) {
int[][] mat = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
int[][] flipped = rotate(mat);

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {
System.out.print(" " + flipped[i][j]);
}

System.out.println();
}
}

public static int[][] rotate(int[][] inMatrix) {
int[][] outMatrix = new int[3][3];

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {
outMatrix[i][j] = inMatrix[j][i];
}
}

return outMatrix;
}
}

No comments: