package cn.allan.y;
import java.util.ArrayList;
public class Solution {
public static ArrayList<Integer> printMatrix(int[][] matrix) {
ArrayList<Integer> a = new ArrayList<>();
if (matrix.length == 0 || matrix[0].length == 0) return a;
int i, left = 0, top = 0, right = matrix[0].length - 1, bottom = matrix.length - 1;
while (left <= right && top <= bottom) {
for (i = left; i <= right; i++) a.add(matrix[top][i]);
top++;
for (i = top; i <= bottom; i++) a.add(matrix[i][right]);
right--;
if (top - 1 == bottom || left == right + 1) break;
for (i = right; i >= left; i--) a.add(matrix[bottom][i]);
bottom--;
for (i = bottom; i >= top; i--) a.add(matrix[i][left]);
left++;
}
return a;
}
public static void main(String[] args) {
int[][] a = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
System.out.println(printMatrix(a));
}
}
题源:www.nowcoder.com/practice/9b…