Closed skanagavelu closed 8 years ago
This code will not support rectangular matrix something like below.
int[][] m = { {1, 2, 3, 4, 40}, {5, 6, 7, 8, 50}, {9, 10, 11, 12, 60}, {13, 14, 15, 16, 70}, {17, 18, 19, 20, 80}, {21, 22, 23, 24, 90}, {25, 26, 27, 28, 100}, {29, 30, 31, 32, 110}, {33, 34, 35, 36, 120}};
My code is below.
/** * The solution is simple and it will solve all type [RECTANGLE] or [SQUARE] of matrix. * @param matrix */ private static void printSpiralSolution2(int[][] matrix) { int starti = 0; int startj = 0; int endi = matrix.length - 1; int endj = matrix[0].length - 1; /* * This loop is enough for SQURE matrix * Pass diagonal elements ordinal from start and end e.g: (1,1) (2,2) (3,3) * If diagonal crosses then that is the end point for this. */ for(; starti < endi && startj < endj; starti ++, startj ++, endi --, endj --) { printSpiralSolution2Sub(matrix, starti, startj, endi, endj); System.out.println(); } //This is corner case for matrix with columns are more than rows. if(starti < endj) { for(int l2r = startj; l2r <= endj; l2r ++ ) { System.out.print("[" + matrix[starti][l2r]+ "], "); } } //This is corner case for matrix with rows are more than columns. if(startj < endi) { for(int t2b = starti; t2b <= endi; t2b ++ ) { System.out.print("[" + matrix[t2b][endj]+ "], "); } } //Corner case for center of element in square oddNumber*oddNumber matrix if(starti == endj && startj == endi) { System.out.println("[" +matrix[starti][starti]+ "], "); } } private static void printSpiralSolution2Sub(int[][] matrix, int starti, int startj, int endi, int endj) { //left 2 right for(int l2r = startj; l2r < endj; l2r ++ ) { System.out.print("[" + matrix[starti][l2r]+ "], "); } //top 2 bottom for(int t2b = starti; t2b < endi; t2b ++ ) { System.out.print("[" + matrix[t2b][endj]+ "], "); } //right 2 left for(int r2l = endj; r2l > startj; r2l -- ) { System.out.print("[" + matrix[endi][r2l]+ "], "); } //bottom 2 top for(int b2t = endi; b2t > starti; b2t -- ) { System.out.print("[" + matrix[b2t][startj]+ "], "); } }
This code will not support rectangular matrix something like below.
My code is below.