GoThroughMatrixInSpiral { public int[] go(int[][] matrix) { if (matrix == null) { throw new IllegalArgumentException("You can't pass a null insantece as input."); } if (matrix.length == 0) { return new int[0]; } int m = matrix.length; int n = matrix[0].length; int resultIndex = 0; int[] result = new int[m * n]; int x = 0; int y = 0; while (m > 0 && n > 0) { if (m == 1) { for (int i = 0; i < n; i++) { result[resultIndex++] = matrix[x][y]; y++; } break; } else if (n == 1) { for (int i = 0; i < m; i++) { result[resultIndex++] = matrix[x][y]; x++; } break; } for (int i = 0; i < n - 1; i++) { result[resultIndex++] = matrix[x][y]; y++; } for (int i = 0; i < m - 1; i++) { result[resultIndex++] = matrix[x][y]; x++; } for (int i = 0; i < n - 1; i++) { result[resultIndex++] = matrix[x][y]; y--; } for (int i = 0; i < m - 1; i++) { result[resultIndex++] = matrix[x][y]; x--; } x++; y++; m = m - 2; n = n - 2; } return result; }  int[] go(int[][] matrix);  }
@Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullInstancesAsInput() { goThroughMatrixInSpiral.go(null); }
@Test public void shouldReturnEmptyArrayIfMatrixIsEmpty() { int[][] matrix = { }; int[] result = goThroughMatrixInSpiral.go(matrix); assertEquals(0, result.length); }
@Test public void shouldGoThroughTheMatrixInSpiral() { int[][] matrix = { { 1, 2, 3, 4, 5, 6 }, { 20, 21, 22, 23, 24, 7 }, { 19, 32, 33, 34, 25, 8 }, { 18, 31, 36, 35, 26, 9 }, { 17, 30, 29, 28, 27, 10 }, { 16, 15, 14, 13, 12, 11 } }; int[] result = goThroughMatrixInSpiral.go(matrix); int[] expected = { 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 }; assertArrayEquals(expected, result); }