SpiralMatrix { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> list = new ArrayList<>(); if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return list; } int m = matrix.length, n = matrix[0].length; int l = (Math.min(m, n) + 1) / 2; for (int i = 0; i < l; i++) { int r = i, c = i; int di = 0; do { list.add(matrix[r][c]); switch (di) { case 0: if (c == n - i - 1) { di = 1; r++; } else { c++; } break; case 1: if (r == m - i - 1) { di = 2; c--; } else { r++; } break; case 2: if (c == i) { di = 3; r--; } else { c--; } break; case 3: if (r == i) { di = 0; } else { r--; } break; } if (r == i - 1 || r == m - i || c == i - 1 || c == n - i) { break; } } while (r != i || c != i); } return list; }  List<Integer> spiralOrder(int[][] matrix); int[][] generateMatrix(int n);  }
@Test(dataProvider = "matrixToSpiralLine") public void test1(int[][] matrix, List<Integer> expectedSpiral) { assertEquals(new SpiralMatrix().spiralOrder(matrix), expectedSpiral); }