链接
牛客:顺时针打印矩阵
LeetCode:剑指 Offer 29. 顺时针打印矩阵
思路
难点在于边界的处理,容易出现数组越界问题,自己画图思考下。
代码
牛客:
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int[][] array) {
ArrayList<Integer> result = new ArrayList<Integer>();
if (array.length == 0) return result;
int n = array.length, m = array[0].length;
if (m == 0) return result;
int layers = (Math.min(n, m) - 1) / 2 + 1;//这个是层数
for (int i = 0; i < layers; i++) {
for (int k = i; k < m - i; k++)
result.add(array[i][k]);//左至右
for (int j = i + 1; j < n - i; j++)
result.add(array[j][m - i - 1]);//右上至右下
for (int k = m - i - 2; (k >= i) && (n - i - 1 != i); k--)
result.add(array[n - i - 1][k]);//右至左
for (int j = n - i - 2; (j > i) && (m - i - 1 != i); j--)
result.add(array[j][i]);//左下至左上
}
return result;
}
}
LeetCode:
class Solution {
public int[] spiralOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return new int[0];
}
int rows = matrix.length, columns = matrix[0].length;
int[] order = new int[rows * columns];
int index = 0;
int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
while (left <= right && top <= bottom) {
for (int column = left; column <= right; column++) {
order[index++] = matrix[top][column];
}
for (int row = top + 1; row <= bottom; row++) {
order[index++] = matrix[row][right];
}
if (left < right && top < bottom) {
for (int column = right - 1; column > left; column--) {
order[index++] = matrix[bottom][column];
}
for (int row = bottom; row > top; row--) {
order[index++] = matrix[row][left];
}
}
left++;
right--;
top++;
bottom--;
}
return order;
}
}