螺旋矩阵

链接
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素

import java.util.*;


public class Solution {
    public int[] SpiralMatrix(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return new int[0];
        }
        int n = matrix.length, m = matrix[0].length;
        int[] ret = new int[n * m];

        int row1 = 0, col1 = 0, row2 = n - 1, col2 = m - 1;

        int index = 0;
        while (row1 <= row2 && col1 <= col2) {
            if (row1 == row2) {
                for (int i = col1; i <= col2; ++i) {
                    ret[index++] = matrix[row1][i];
                }
            } else if (col1 == col2) {
                for (int i = row1; i <= row2; ++i) {
                    ret[index++] = matrix[i][col1];
                }
            } else {
                for (int i = col1; i < col2; ++i) {
                    ret[index++] = matrix[row1][i];
                }

                for (int i = row1; i < row2; ++i) {
                    ret[index++] = matrix[i][col2];
                }

                for (int i = col2; i > col1; --i) {
                    ret[index++] = matrix[row2][i];
                }

                for (int i = row2; i > row1; --i) {
                    ret[index++] = matrix[i][col1];
                }

            }

            row1++;
            col1++;
            row2--;
            col2--;
        }

        return ret;
    }
}
上一篇:Pytorch ----- 数据集 (dataset) 数据加载器 (dataloader) num_workeres工作原理 及调整方法 ~~学习笔记


下一篇:roadrunner中文文档(二)PHP Workers