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
| package algorithm;
import java.util.ArrayList; import java.util.List;
public class SpiralMatrix {
public static List<Integer> spiralOrder(int[][] matrix) { List<Integer> ans = new ArrayList<>(); if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return ans; } int rows = matrix.length; int cols = matrix[0].length; int left = 0; int right = cols - 1; int top = 0; int bottom = rows - 1; while (left <= right && top <= bottom) { for (int column = left; column <= right; column ++) { ans.add(matrix[top][column]); } for (int row = top + 1; row <= bottom; row ++) { ans.add(matrix[row][right]); } if (left < right && top < bottom) { for (int column = right - 1; column > left; column --) { ans.add(matrix[bottom][column]); } for (int row = bottom; row > top; row --) { ans.add(matrix[row][left]); } } top ++; right --; bottom --; left ++; }
return ans; }
public static void main(String[] args) { int[][] matrix = new int[][]{{1,2,3},{4,5,6},{7,8,9}}; System.out.println(spiralOrder(matrix));
matrix = new int[][] {{1,2,3,4},{5,6,7,8},{9,10,11,12}}; System.out.println(spiralOrder(matrix));
matrix = new int[][]{{1,2,3,4,5,6,7,8,9,10},{11,12,13,14,15,16,17,18,19,20}}; System.out.println(spiralOrder(matrix)); } }
|