Print a given matrix in spiral form.
Anónimo
public class PrintSpiral { public static void main(String[] args) { int rows = 4; int cols = 5; int[][] matrix = filledMatrix(rows, cols); printMatrix(matrix); printSpiral(matrix); } static int[][] filledMatrix(int rows, int cols) { int[][] matrix = new int[rows][cols]; int n = 0; for (int row = 0; row 0) { System.out.print("-"); } } System.out.println(); } static void printSpiral(int[][] matrix) { int rows = matrix.length; int cols = matrix[0].length; String direction = "left-to-right"; int row, col; for (int pass = 0; pass = pass ; col--) { System.out.printf("%2d ", matrix[row][col]); } direction = "bottom-to-top"; break; case "bottom-to-top": col = pass; for (row = rows - pass - 2; row > pass; row--) { System.out.printf("%2d ", matrix[row][col]); } direction = "left-to-right"; pass++; break; } } System.out.println(); } }