Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 88d25bb

Browse files
author
Ram swaroop
committed
print spiral matrix almost done
1 parent 22274ed commit 88d25bb

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

src/me/ramswaroop/arrays/MatrixInSpiral.java

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,23 +11,35 @@
1111
*/
1212
public class MatrixInSpiral {
1313

14+
/**
15+
*
16+
* @param a
17+
*/
1418
public static void printMatrixInSpiral(int[][] a) {
1519
int row = a.length, col = a[0].length;
1620

17-
//for (int r = 0, c = col - 1; r < row && c >= 0; r++, c--) {
18-
for (int i = 0, j = 0; j < col; j++) {
21+
// this loop iterates for the entire matrix
22+
for (int r = row, c = col, x = 0; r >= 0 && c >= 0; r--, c--, x++) {
23+
/**
24+
* Below 4 {@code for} loops print the perimeter of a matrix
25+
*/
26+
// prints the top row
27+
for (int i = x, j = x; i < r && j < c; j++) {
1928
out.print(a[i][j]);
2029
}
21-
for (int i = 1, j = col - 1; i < row; i++) {
30+
// prints the right most column
31+
for (int i = x + 1, j = c - 1; i < r; i++) {
2232
out.print(a[i][j]);
2333
}
24-
for (int i = row - 1, j = col - 2; j >= 0; j--) {
34+
// prints the bottom row
35+
for (int i = r - 1, j = c - 2; j >= x; j--) {
2536
out.print(a[i][j]);
2637
}
27-
for (int i = row - 2, j = 0; i > 0; i--) {
38+
// prints the left most column
39+
for (int i = r - 2, j = x; i > x; i--) {
2840
out.print(a[i][j]);
2941
}
30-
//}
42+
}
3143
}
3244

3345
public static void main(String a[]) {

0 commit comments

Comments
 (0)