java打印回文矩阵,Leet Code 54 Spiral Matrix - 螺旋输出矩阵 - Java

给定一个 m*n 的矩阵,以螺旋顺序返回该矩阵的所有元素。

例如,给定矩阵:

[

[ 1, 2, 3 ],

[ 4, 5, 6 ],

[ 7, 8, 9 ]

]

返回 [1,2,3,6,9,8,7,4,5]。

思路:从外到内分圈处理。

public class Solution {

public static List spiralOrder(int[][] matrix) {

List result = new ArrayList();

if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {

return result;

}

int topRow = 0;

int leftCol = 0;

int bottomRow = matrix.length - 1;

int rightCol = matrix[0].length - 1;

while (topRow <= bottomRow && leftCol <= rightCol) {

spiralOrderCircle(matrix, topRow, leftCol, bottomRow, rightCol, result);

topRow++;

leftCol++;

bottomRow--;

rightCol--;

}

return result;

}

private static void spiralOrderCircle(int[][] matrix, int topRow,

int leftCol, int bottomRow, int rightCol, List result) {

if (topRow == bottomRow) {

spiralOrderRow(matrix, topRow, leftCol, rightCol, result);

} else if (leftCol == rightCol) {

spiralOrderCol(matrix, leftCol, topRow, bottomRow, result);

} else {

spiralOrderTop(matrix, topRow, leftCol, bottomRow, rightCol, result);

spiralOrderRight(matrix, topRow, leftCol, bottomRow, rightCol, result);

spiralOrderBottom(matrix, topRow, leftCol, bottomRow, rightCol, result);

spiralOrderLeft(matrix, topRow, leftCol, bottomRow, rightCol, result);

}

}

private static void spiralOrderRow(int[][] matrix, int row, int leftCol,

int rightCol, List result) {

for (int col = leftCol; col <= rightCol; col++) {

result.add(matrix[row][col]);

}

}

private static void spiralOrderCol(int[][] matrix, int col, int topRow,

int bottomRow, List result) {

for (int row = topRow; row <= bottomRow; row++) {

result.add(matrix[row][col]);

}

}

private static void spiralOrderTop(int[][] matrix, int topRow, int leftCol,

int bottomRow, int rightCol, List result) {

for (int col = leftCol; col < rightCol; col++) {

result.add(matrix[topRow][col]);

}

}

private static void spiralOrderRight(int[][] matrix, int topRow, int leftCol,

int bottomRow, int rightCol, List result) {

for (int row = topRow; row < bottomRow; row++) {

result.add(matrix[row][rightCol]);

}

}

private static void spiralOrderBottom(int[][] matrix, int topRow,

int leftCol, int bottomRow, int rightCol, List result) {

for (int col = rightCol; col > leftCol; col--) {

result.add(matrix[bottomRow][col]);

}

}

private static void spiralOrderLeft(int[][] matrix, int topRow, int leftCol,

int bottomRow, int rightCol, List result) {

for (int row = bottomRow; row > topRow; row--) {

result.add(matrix[row][leftCol]);

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值