|
| 1 | +import java.util.Arrays; |
| 2 | +import java.util.List; |
| 3 | + |
| 4 | +public class Solution { |
| 5 | + |
| 6 | + public static void main(String[] args) { |
| 7 | + Solution s = new Solution(); |
| 8 | +// System.out.println(List.of(s.spiralTravel(new int[][]{{1, 2, 3}, {4, 5, 6}}))); |
| 9 | + System.out.println(List.of(s.spiralTravel(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}))); |
| 10 | +// System.out.println(List.of(s.spiralTravel(new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}))); |
| 11 | + } |
| 12 | + |
| 13 | + public Integer[] spiralTravel(int[][] numsArray) { |
| 14 | + if (numsArray == null || numsArray.length == 0 || numsArray[0] == null) { |
| 15 | + return null; |
| 16 | + } |
| 17 | + int total = 0; |
| 18 | + int length = numsArray[0].length; |
| 19 | + for (int[] nums : numsArray) { |
| 20 | + if (nums == null) { |
| 21 | + throw new IllegalArgumentException("have null arrays"); |
| 22 | + } |
| 23 | + if (nums.length != length) { |
| 24 | + throw new IllegalArgumentException("not have same length"); |
| 25 | + } |
| 26 | + total += nums.length; |
| 27 | + } |
| 28 | + int top = 0, left = numsArray[0].length, bottom = numsArray.length, right = 0; |
| 29 | + int count = 0; |
| 30 | + Integer[] res = new Integer[total]; |
| 31 | + while (count < total) { |
| 32 | + int j = top; |
| 33 | + int i = right; |
| 34 | + for (; i < left; i++) { |
| 35 | + res[count++] = numsArray[j][i]; |
| 36 | + } |
| 37 | + i = left - 1; |
| 38 | + for (j = top + 1; j < bottom; j++) { |
| 39 | + res[count++] = numsArray[j][i]; |
| 40 | + } |
| 41 | + j = bottom - 1; |
| 42 | + for (i = left - 2; i >= right; i--) { |
| 43 | + res[count++] = numsArray[j][i]; |
| 44 | + } |
| 45 | + i = right; |
| 46 | + for (j = bottom - 2; j > top; j--) { |
| 47 | + res[count++] = numsArray[j][i]; |
| 48 | + } |
| 49 | + top = top + 1; |
| 50 | + left = left - 1; |
| 51 | + bottom = bottom -1; |
| 52 | + right = right + 1; |
| 53 | + } |
| 54 | + |
| 55 | + return res; |
| 56 | + } |
| 57 | +} |
0 commit comments