Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Spiralize a 2D square matrix i.e nxn matrix
public class SpiralMatrix {
/*
Problem:
Spiralize a 2D square matrix i.e (nxn)
input: 123
456
789
result: 123
894
765
*/
public static void main(String[] args) {
int size = 3;
int[][] matrix = new int[size][size];
int len = matrix.length;
int seed = 1;
int indexValue = seed;
int rowOffset = 0;
//spiralize 2D square matrix (nxn)
for (int k = 1; k <= 2; k++) {
if (k == 1)
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
if (i == 0) {
matrix[i][j] = seed++;
indexValue = seed;
} else if (i > 0) {
matrix[i][len - 1] = indexValue;
indexValue++;
break;
}
}
}
else
for (int i = len; i >= 0; i--) {
if (i > 1 && rowOffset == 0) {
for (int j = len; j >= 0; j--) {
if (i > 0 && j < len - 1) {
matrix[i - 1][j] = indexValue;
indexValue++;
}
}
rowOffset = 1;
} else if (i > 1 && rowOffset == 1) {
for (int j = 0; j < len; j++) {
if (i > 0 && j < len - 1) {
matrix[i - 1][j] = indexValue;
indexValue++;
}
}
rowOffset = 0;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment