模板
打印图示:
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
if (matrix == null || (matrix.length == 0 && matrix[0].length == 0)) return res;
int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
while (left <= right && top <= bottom) {
for (int column = left; column <= right; column++) {
res.add(matrix[top][column]);
}
for (int row = top + 1; row <= bottom; row++) {
res.add(matrix[row][right]);
}
// if判断是根据是否时正方形,如果不是需要判断,如果是就不需要判断
if (left < right && top < bottom) {
for (int column = right - 1; column >= left + 1; column--) {
res.add(matrix[bottom][column]);
}
for (int row = bottom; row >= top + 1; row--) {
res.add(matrix[row][left]);
}
}
top++;
bottom--;
left++;
right--;
}
return res;
}
}
59.矩阵模拟II
public int[][] generateMatrix(int n) {
int[][] array = new int[n][n];
int top = 0, bottom = n - 1, left = 0, right = n - 1;
int count = 1;
while (left <= right && top <= bottom) {
for (int column = left; column <= right; column++) {
array[top][column] = count++;
}
for (int row = top + 1; row <= bottom; row++) {
array[row][right] = count++;
}
for (int column = right - 1; column >= left + 1; column--) {
array[bottom][column] = count++;
}
for (int row = bottom; row >= top + 1; row--) {
array[row][left] = count++;
}
top++;
bottom--;
left++;
right--;
}
return array;
}
54.螺旋矩阵
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if (matrix == null || (matrix.length == 0 && matrix[0].length == 0)) return res;
int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
while (left <= right && top <= bottom) {
for (int column = left; column <= right; column++) {
res.add(matrix[top][column]);
}
for (int row = top + 1; row <= bottom; row++) {
res.add(matrix[row][right]);
}
if (left < right && top < bottom) {
for (int column = right - 1; column >= left + 1; column--) {
res.add(matrix[bottom][column]);
}
for (int row = bottom; row >= top + 1; row--) {
res.add(matrix[row][left]);
}
}
top++;
bottom--;
left++;
right--;
}
return res;
}
剑指 Offer 29. 顺时针打印矩阵
public int[] spiralOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return new int[]{};
}
List<Integer> list = new ArrayList<>();
int rows = matrix.length, columns = matrix[0].length; // 行列的数量
int top = 0, button = rows - 1, right = columns - 1, left = 0;
while (left <= right && top <= button) {
// 遍历上边
for (int column = left; column <= right; column++) {
list.add(matrix[top][column]);
}
// 遍历右边
for (int row = top + 1; row <= button; row++) {
list.add(matrix[row][right]);
}
if (left < right && top < button) {
// 遍历下边
for (int column = right - 1; column > left; column--) {
list.add(matrix[button][column]);
}
// 遍历左边
for (int row = button; row > top; row--) {
list.add(matrix[row][left]);
}
}
left++;
right--;
top++;
button--;
}
int[] ints = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
ints[i] = list.get(i);
}
return ints;
}