Last active
July 3, 2018 05:11
-
-
Save knasim/62f2bd1755739cb687f911d9ea801fa9 to your computer and use it in GitHub Desktop.
Spiralize a 2D square matrix i.e nxn matrix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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