1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| public class Jz29_2 { public static void main(String[] args) { final Jz29_3_1 jz = new Jz29_3_1(); System.out.println(jz.printMatrix(new int[][]{ {1, 2, 3, 1}, {4, 5, 6, 1}, {4, 5, 6, 1}, }));
System.out.println(jz.printMatrix(new int[][]{ {1}, {2}, {3}, {4}, {5} }));
System.out.println(jz.printMatrix(new int[][]{ {1, 2, 3, 4, 5} }));
System.out.println(jz.printMatrix(new int[][]{ {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} })); }
public ArrayList<Integer> printMatrix(int[][] matrix) { if (matrix == null || matrix.length == 0) { return new ArrayList<>(); }
ArrayList<Integer> list = new ArrayList<>(matrix.length * matrix[0].length); int minX = 0; int maxX = matrix.length - 1; int minY = 0; int maxY = matrix[0].length - 1;
int x, y; while (minX <= maxX && minY <= maxY) { boolean down = false; boolean left = false;
for (x = minX, y = minY; y <= maxY; y++) { list.add(matrix[x][y]); }
for (x = minX + 1, y = maxY; x <= maxX; x++) { list.add(matrix[x][y]); down = true; }
for (x = maxX, y = maxY - 1; down && y >= minY; y--) { list.add(matrix[x][y]); left = true; }
for (x = maxX - 1, y = minY; left && x > minX; x--) { list.add(matrix[x][y]); }
minX++; maxX--; minY++; maxY--; }
return list; } }
|