Skip to content

Instantly share code, notes, and snippets.

@taylorleese
Created March 19, 2011 08:14
Show Gist options
  • Save taylorleese/877326 to your computer and use it in GitHub Desktop.
Save taylorleese/877326 to your computer and use it in GitHub Desktop.
Print matrix in spiral order.
public class Spiral {
public static void main(String[] args) {
int row = Integer.parseInt(args[0]);
int col = Integer.parseInt(args[1]);
int[][] matrix = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
matrix[i][j] = i * col + j + 1;
}
}
for (int i = col - 1, j = row - 1, k = 0; i >= 0 && j >= 0; i--, j--, k++) {
for (int l = k; l < i; l++) { // right
System.out.print(matrix[k][l]+ " ");
}
for (int l = k; l < j; l++) { // down
System.out.print(matrix[l][i]+ " ");
}
for (int l = i; l > k; l--) { // left
System.out.print(matrix[j][l]+ " ");
}
for (int l = j; l > k; l--) { // up
System.out.print(matrix[l][k]+ " ");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment