Examples:
Input 1 2 3 4 5 6 7 8 9 Output: 4 1 2 7 5 3 8 9 6 For 4*4 matrix Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 5 1 2 3 9 10 6 4 13 11 7 8 14 15 16 12
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | package array; public class RotateMatrixElement { static void rotateMatrixElement(int matrix[][]) { // dynamically changing row and col boundaries int bottomRow = matrix.length;// end row int rightCol = matrix[0].length; // end col int topRow = 0;// Staring row index int leftCol = 0;// /ending row index int prev, curr;// previous and current element while (topRow < bottomRow && leftCol < rightCol) { if (topRow + 1 == bottomRow || leftCol + 1 == rightCol) break; // get the first element of next row, which // will replace first element of current row prev = matrix[topRow + 1][leftCol]; /* Move elements of first row from unprocessed rows */ // for row, we move columns for (int i = leftCol; i < rightCol; i++) { // swap current element with previous element curr = matrix[topRow][i]; matrix[topRow][i] = prev; prev = curr;// make current element as previous element after // one swap }// this processes entire first unprocessed row topRow++;// thus rows becomes row /* * Move elements of last column from the unprocessed columns * --according to spiral order */ // for column, we move rows for (int i = topRow; i < bottomRow; i++) { // keep updating current and previous values curr = matrix[i][rightCol - 1]; matrix[i][rightCol - 1] = prev; prev = curr; } // right column is processed over, column boundary need to be // changed rightCol--;// right boundary shrinks towards left boundary /* Move elements of last row from the unprocessed rows */ if (topRow < bottomRow) { for (int i = rightCol - 1; i >= leftCol; i--) { curr = matrix[bottomRow - 1][i]; matrix[bottomRow - 1][i] = prev; prev = curr; } } // row is processed from bottom bottomRow--; /* Move elements of left first column from the unprocessed columns */ // it is column, row is moving from bottom to top if (leftCol < rightCol) { for (int i = bottomRow - 1; i >= topRow; i--) { curr = matrix[i][leftCol]; matrix[i][leftCol] = prev; prev = curr; } } leftCol++; } } public static void printArray(int[][] matrix) { System.out.println(matrix.length); for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix.length; j++) System.out.print(matrix[i][j] + " "); System.out.println(); } } public static void main(String[] args) { // Test Case 1 // int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, // { 13, 14, 15, 16 } }; int a[][] = { { 1, 2 }, { 3, 4 } }; printArray(a); rotateMatrixElement(a); printArray(a); } } |
No comments:
Post a Comment